本文介绍了使用Numpy数组的Opencv Python裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using OpenCV 3.1.0-dev and python 2.7.

我试图裁剪出我缝合的图像的黑色外观.难题在于图像中还有其他黑色像素,因此cv2.findcontours返回一个非常有趣的numpy数组.

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.

我想知道是否有人知道如何将多边形裁剪为包含整个图像的最小正方形.蓝线和点是cv2.findContours找到的轮廓.是否有可能在numpy数组中找到最左上角的点,并在我可以裁剪的numpy数组中找到最右下角的p0int?如果是这样,我该怎么办.

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.

这是我当前的代码.我正在尝试使用cnt=contours[0]

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()

感谢任何帮助

推荐答案

一旦有了contours,就可以列出它们的xy,然后找到最大值和最小值:

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]

(x1, y1)是左上角,(x2, y2)是右下角.

The (x1, y1) would be the top left corner and the (x2, y2) the bottom right.

希望这对您有帮助!

这篇关于使用Numpy数组的Opencv Python裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 05:43