【问题标题】:Cropping an image after detecting the contours using opencv python使用opencv python检测轮廓后裁剪图像
【发布时间】: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 是空的,这很奇怪,因为当我打印topxtopybottomxbottomy 时,我得到了整数,所以逻辑裁剪会给我一个结果。

【问题讨论】:

  • @bechirjamoussi 您在 SO 的文本编辑器中有一个工具可以将您的文本作为代码。每行前带有表格的文本将被格式化为代码。

标签: python opencv machine-learning image-processing


【解决方案1】:

通常,如果您检测到轮廓,您可以通过在代码中添加以下行来裁剪轮廓,就在contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 之后:

i = 0
for c in contours:
    # get the bounding rect
    x, y, w, h = cv2.boundingRect(c)
    # to save the images
    cv2.imwrite('img_{}.jpg'.format(i), image[y:y+h,x:x+w])
    i += 1

【讨论】:

  • 欢迎贝奇:p
【解决方案2】:

你可以试试这个:

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]

来源:https://stackoverflow.com/questions/41069831/opencv-python-crop-image-using-numpy-array?rq=1#=

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2014-07-27
    • 2021-07-12
    • 2014-04-24
    • 1970-01-01
    相关资源
    最近更新 更多