I am using OpenCV 3.1.0-dev and python 2.7.
I am trying to crop out the black exterior of an image I have stitched. The struggle is that there are other pixels in the image that are black so cv2.findcontours returns a very interesting numpy array.
The first image is what I have and the 2nd image is the target.
I was wondering if someone knew how to crop a polygon into the smallest square containing the entire image. The blue lines and points are the contours found by cv2.findContours. Is it possibly to find the top-left most point in the numpy array and the bottom-right most p0int in a numpy array that I can crop to? If so, how do I do it.
Here is my current code. I am trying to find the point to crop with cnt=contours[0]
import cv2
import numpy as np
img = cv2.imread("/Users/chrisradford/Documents/Research/ImagesToPass/masterToCrop.jpg",1)
grayed = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
(_,thresh) = cv2.threshold(grayed,1,255,cv2.THRESH_BINARY)
result, contours, _= cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
# (x,y) = top left coordinate & w,h = idth and height
x,y,w,h = cv2.boundingRect(cnt) #good
cropped = img[y:y+h,x:x+w] #good
cv2.drawContours(img,contours,-1,(255,0,0),3)
cv2.imshow("result",img)
cv2.imwrite('/Users/chrisradford/Documents/Research/ImagesToPass/StackOverflow.jpg',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Any Help is Appreciated
There is no specific function for cropping using OpenCV, NumPy array slicing is what does the job. Every image that is read in, gets stored in a 2D array (for each color channel). Simply specify the height and width (in pixels) of the area to be cropped. And it's done!
crop() method is used to crop a rectangular portion of any image. Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate. Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple).
From PythonImport the Cropper class, set some parameters (optional), and start cropping. The crop method accepts filepaths or np. ndarray , and returns Numpy arrays. These are easily handled with PIL or Matplotlib.
Explanation: We use cv2. CascadeClassifier for load haarcascade file in face_cascade. detectMultiScale() function used for detect faces.It takes 3 parameters: Gray: input image(gray scale image)
Once you have the contours
, you can do a list of the x
and the y
of them and then find the maximum and minimum:
x, y = [], []
for contour_line in contours:
for contour in contour_line:
x.append(contour[0][0])
y.append(contour[0][1])
x1, x2, y1, y2 = min(x), max(x), min(y), max(y)
cropped = img[y1:y2, x1:x2]
The (x1, y1)
would be the top left corner and the (x2, y2)
the bottom right.
Hope this helped!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With