Opencv Python 使用 Numpy 数组裁剪图像

Opencv Python Crop Image Using Numpy Array

我正在使用 OpenCV 3.1.0-dev 和 python 2.7。

我正在尝试剪掉拼接图像的黑色外观。困难在于图像中还有其他黑色像素,因此 cv2.findcontours returns 一个非常有趣的 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/Whosebug.jpg',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

感谢任何帮助

获得 contours 后,您可以列出 xy,然后找出最大值和最小值:

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) 是右下角。

希望对您有所帮助!