Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在自己的窗口中显示图像的每个对象_Python_Opencv_Bounding Box - Fatal编程技术网

Python:在自己的窗口中显示图像的每个对象

Python:在自己的窗口中显示图像的每个对象,python,opencv,bounding-box,Python,Opencv,Bounding Box,我已经编写了一些代码,用于从图像中裁剪对象(在本例中为数据矩阵代码): 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, thr

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

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

代码运行良好,因此我收到:

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


是否有一种更简单的方法可以让每个对象都显示在窗口中?

对于这张特定的图像,请获取您拥有的最大轮廓,并检查对象是否为四边形。如果边界框角之间的半点(参见下面的对)位于轮廓阵列中,那么瞧,问题解决了

成对:上右上左、上右下右、上左下左、下左下右

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

对于单独的绘图,只需在您准备好的东西上打一记耳光

这个怎么样

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)