【发布时间】:2019-12-06 16:50:10
【问题描述】:
我正在尝试在检测到轮廓后裁剪图像,然后使用 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)
数组out 是空的,这很奇怪,因为当我打印topx、topy、bottomx 和bottomy 时,我得到了整数,所以逻辑裁剪会给我一个结果。
【问题讨论】:
-
@bechirjamoussi 您在 SO 的文本编辑器中有一个工具可以将您的文本作为代码。每行前带有表格的文本将被格式化为代码。
标签: python opencv machine-learning image-processing