首页 > 解决方案 > Python:在自己的窗口中显示图像的每个对象

问题描述

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

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()

第一图像数据矩阵

代码工作正常,我收到了结果:

我的 Python 代码的结果

但是,下一个图像要复杂一些。我收到与上一张图片相同的结果,但我不知道如何检测另外两个对象。

具有三个对象的第二张图像

每个对象都显示在其窗口中是否有更简单的方法?

标签: pythonopencvbounding-box

解决方案


对于这个特定的图像,取你拥有的最大轮廓并检查对象是否是 4 边形状。如果边界框角之间的半点(见下面的对)在轮廓数组中,那么问题就解决了。

对:TopRight-TopLeft、TopRight-BottomRight、TopLeft-BottomLeft、BottomLeft-BottomRight

或者您可以检查边界框内是否有非黑色/白色的像素?

而对于策划个人来说,只需为你已经拥有的东西打一巴掌


推荐阅读