对象高度和宽度上的裁剪二进制图像

问题描述 投票:0回答:2

我有这个形象:character

我已成功隔离了角色,现在我想将图像裁剪为二进制对象的边界。这是我想要裁剪的清理图像:edited

我似乎无法弄清楚代码。这是我尝试过的:

inv = cv2.bitwise_not(img)
mask = np.zeros(img.shape, np.uint8)
_, cnts, hier = cv2.findContours(img.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
    if cv2.contourArea(c) > 100:
        cv2.drawContours(mask, [c], 0, 255, -1)
        x, y, h, w = cv2.boundingRect(c)
        roi = mask[y:y + h, x:x + w]
        crop = img[y:y + h, x:x + w]
        final = crop * (roi / 255)
python-3.x opencv
2个回答
0
投票

你可以简单地使用max来找到最大的轮廓和cv2.boundingRect来找到最大轮廓的坐标,之后你可以裁剪它。

c = max(contours, key = cv2.contourArea)
x,y,w,h = cv2.boundingRect(c)

在这种情况下使用cv2.RETR_EXTERNAL时使用cv2.RETR_LIST而不是cv2.findContours会更好,因为它只是在寻找对象的边界而不是内部细节。


0
投票

如果你想用点(x1,y1)和(x2,y2)裁剪图像

(x1,y1)+-------+
       |       |
       |       |
       +-------+(x2,y2)
## mask is a numpy array (an image)
croped_image = mask[y1:y2, x1:x2] ## this will return a cropped image

但对于你的问题,你想要边界矩形裁剪二进制图像我猜

见:https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html

_, contours, _ = cv2.findContours( mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE )
contour        = max(contours, key = cv2.contourArea)
x, y, w, h     = cv2.boundingRect(contour)
x1, y1, x2, y2 = x, y, x+w, y+h

现在使用这些点来裁剪图像

© www.soinside.com 2019 - 2024. All rights reserved.