我正在使用 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()
感谢任何帮助
最佳答案
一旦你有了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]
(x1, y1)
位于左上角,(x2, y2)
位于右下角。
希望这对您有所帮助!
关于python - Opencv Python 使用 Numpy 数组裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069831/