且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用OpenCV检测图像帧中的对象?

更新时间:2022-01-28 08:44:29

我怀疑这个问题是否像您在问题中描述的那么简单,当我们进入现实世界的场景时,它会变得非常复杂。

但无论如何,假设您的小对象只出现在房间中,那么您可以通过识别捕获的二进制图像中的连接组件并根据它们的相对像素大小选择它们来识别它们。

下面是相同的Python实现:

img = cv2.imread('D:/Image/objects.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# binarize the image
ret, bw = cv2.threshold(gray, 128, 255, 
cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# find connected components
connectivity = 4
nb_components, output, stats, centroids = 
cv2.connectedComponentsWithStats(bw, connectivity, cv2.CV_32S)
sizes = stats[1:, -1]; nb_components = nb_components - 1
min_size = 250 #threshhold value for objects in scene
img2 = np.zeros((img.shape), np.uint8)
for i in range(0, nb_components+1):
    # use if sizes[i] >= min_size: to identify your objects
    color = np.random.randint(255,size=3)
    # draw the bounding rectangele around each object
    cv2.rectangle(img2, (stats[i][0],stats[i][1]),(stats[i][0]+stats[i][2],stats[i][1]+stats[i][3]), (0,255,0), 2)
    img2[output == i + 1] = color

包含对象的图像:

使用连接的组件标签检测到的对象: