C.R*_*ord 4 python arrays opencv numpy crop
我正在使用OpenCV 3.1.0-dev和python 2.7.
我试图裁剪出我缝制的图像的黑色外观.困难在于图像中有其他像素是黑色的,所以cv2.findcontours返回一个非常有趣的numpy数组.
第一张图片是我的,第二张图片是目标.
我想知道是否有人知道如何将多边形裁剪到包含整个图像的最小正方形中.蓝线和点是cv2.findContours找到的轮廓.是否可以在numpy数组中找到左上角最多的点,在numpy数组中找到最右下角的p0int,我可以裁剪到?如果是这样,我该怎么做.
这是我目前的代码.我试图找到与作物有关的点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()
Run Code Online (Sandbox Code Playgroud)
任何帮助都会得到赞赏
获得后contours,您可以列出x其中y的一个,然后查找最大值和最小值:
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]
Run Code Online (Sandbox Code Playgroud)
在(x1, y1)将左上角和(x2, y2)右下角.
希望这有帮助!