Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用opencv python检测轮廓后裁剪图像_Python_Opencv_Machine Learning_Image Processing - Fatal编程技术网

使用opencv python检测轮廓后裁剪图像

使用opencv python检测轮廓后裁剪图像,python,opencv,machine-learning,image-processing,Python,Opencv,Machine Learning,Image Processing,我试图在检测到轮廓后裁剪图像,然后使用python、opencv和numpy从中提取信息 检测轮廓是成功的,但是我找不到裁剪的方法。我尝试了一些代码,但没有得到我想要的结果: import numpy as np import cv2 image = cv2.imread('2.jpg') # Read in your image blurred=cv2.blur(image,(23,51))#blur the image gray=cv2.cvtColor(blurred,cv2.COLOR_

我试图在检测到轮廓后裁剪图像,然后使用python、opencv和numpy从中提取信息

检测轮廓是成功的,但是我找不到裁剪的方法。我尝试了一些代码,但没有得到我想要的结果:

import numpy as np
import cv2
image = cv2.imread('2.jpg') # Read in your image
blurred=cv2.blur(image,(23,51))#blur the image
gray=cv2.cvtColor(blurred,cv2.COLOR_BGR2GRAY)#gray scale
ret,threshold=cv2.threshold(gray , 2 , 255 , cv2.THRESH_BINARY+cv2.THRESH_OTSU)
contours,hierachy=cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#detect contours
mask = np.zeros_like(image) # Create mask where white is what we want, black otherwise
cv2.drawContours(mask,  contours,  0,  (0 ,0,255),1)
out = np.zeros_like(image) # Extract out the object and place into output image
out[mask == 255] = image[mask == 255]

# Now crop
mask=mask.transpose(2,0,1).reshape(-1,mask.shape[1])
(x, y) = np.where(mask == 255)
(topx, topy) = (np.min(x), np.min(y))
(bottomx, bottomy) = (np.max(x), np.max(y))
topx=topx
topy=topy
bottomx=bottomx
bottomy=bottomy
out = out[topx:bottomx,topy:bottomy]
print(out)

数组输出是空的,这很奇怪,因为当我打印topx、topy、bottomx和bottomy时,我会得到整数,所以逻辑裁剪会给出一个结果。

通常,如果检测到轮廓,可以在轮廓之后,通过在代码中添加以下行来裁剪轮廓,即在轮廓之后,hierarchy=cv2.findcontourthreshold,cv2.RETR_外部,cv2.CHAIN_近似简单:

你可以试试这个:

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]

来源:

@bechirjamoussi您在SO的文本编辑器中有一个工具,可以将您的文本作为代码。每行前带有表格的文本将被格式化为代码。欢迎使用的文本可能重复:p
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]