Python:显示图像中的每个对象 window

Python: Showing every Object of an image in its own window

我写了一些代码,从图像中裁剪对象(在本例中为数据矩阵代码):

import numpy as np
import cv2

image = cv2.imread("datamatrixc.png")
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

img_height, img_width = image.shape[:2]

WHITE = [255, 255, 255]

# Threshold filter
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)

# Get Contours
_, contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Get Last element of the contours object
max = len(contours) - 1

cnt = contours[max]

# Get coordinates for the bounding box  
x, y, w, h = cv2.boundingRect(cnt)

image_region = image[ int(((img_height / 2) - h) / 2) : int(((img_height / 2) - h) / 2 + h), int(x): int(x + w) ]
dmc = cv2.copyMakeBorder(image_region, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value = WHITE)

cv2.imshow("Test", dmc)
cv2.waitKey(0)
cv2.destroyAllWindows()

代码运行良好,我收到了结果:

不过,下一张图片有点复杂。 我收到与上一张图片相同的结果,但我不知道如何检测另外两个物体。

是否有更简单的方法让每个对象都显示在 window 中?

对于这个特定的图像,取你拥有的最大轮廓并检查对象是否是 4 边 shape.If 边界框角之间的半点(见下面的对)在轮廓数组中然后瞧,问题已解决。

对:右上-左上、右上-下右、左上-下左、左下-右下

或者您可以检查边界框内是否有不属于 black/white 的像素?

对于个人策划,只需在您已有的东西上打一个 for

这个怎么样?

import numpy as np
import cv2

image = cv2.imread("datamatrixc.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

ret, bin_img = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

kernel = np.ones((3,3),np.uint8)
closing = cv2.morphologyEx(bin_img, cv2.MORPH_CLOSE, kernel, iterations=4)

n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(bin_img)

size_thresh = 5000

for i in range(1, n_labels):
    if stats[i, cv2.CC_STAT_AREA] >= size_thresh:
        print(stats[i, cv2.CC_STAT_AREA])
        x = stats[i, cv2.CC_STAT_LEFT]
        y = stats[i, cv2.CC_STAT_TOP]
        w = stats[i, cv2.CC_STAT_WIDTH]
        h = stats[i, cv2.CC_STAT_HEIGHT]

        cv2.imshow('img', image[y:y+h, x:x+w])
        cv2.waitKey(0)