如何检测位掩码 Opencv 中的特定对象 Python

How To Detect A Specific Object In A Bitwise Mask Opencv Python

我正在尝试检测图像中的对象并在其周围制作边界框

这就是我要检测的内容:

以下是对您有帮助的特征:

这是我到目前为止所取得的成就:

这是代码:

import cv2
import numpy as np

def nothing(x):
    pass

cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)
cv2.createTrackbar("UH", "Tracking", 255, 255, nothing)
cv2.createTrackbar("US", "Tracking", 255, 255, nothing)
cv2.createTrackbar("UV", "Tracking", 255, 255, nothing)

while True:
    frame = cv2.imread('resultImages/imgCropped.png')
    img = frame.copy()

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    l_h = cv2.getTrackbarPos("LH", "Tracking")
    l_s = cv2.getTrackbarPos("LS", "Tracking")
    l_v = cv2.getTrackbarPos("LV", "Tracking")

    u_h = cv2.getTrackbarPos("UH", "Tracking")
    u_s = cv2.getTrackbarPos("US", "Tracking")
    u_v = cv2.getTrackbarPos("UV", "Tracking")

    l_b = np.array([l_h, l_s, l_v])
    u_b = np.array([u_h, u_s, u_v])

    mask = cv2.inRange(hsv, l_b, u_b)

    res = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow("frame", frame)
    cv2.imshow("mask", mask)
    cv2.imshow("res", res)

    key = cv2.waitKey(1)
    if key == 27:
        break

cv2.destroyAllWindows()

我怎样才能检测到这个物体?

我不太确定你到底想做什么,但我会尽力揭示一些可能对你有帮助的关键方面..

1.At 首先,您可以利用对象位置的提示应用侧面图像的课程裁剪。这将减轻图像中存在的其他类似对象的存在。即:

while True:
    frame = cv2.imread('resultImages/imgCropped.png')#this returns a numpy array
    img = frame.copy()

    #define a thresshold let's say 1/4rth of the full image
    width = frame.shape[1]
    thress = int(np.ceil(width/4))
    left= img[:,:thress]#full height,cropped width 
    right = img[:,-thress:]
    #cropped=np.concatenate([left,right])#actually you don't have to merge

2.Since 你可以区分你想要的信息 (black/white),你可以尝试使用 opencv contour features. You could also give a look at this tutorial 来获取图像的轮廓。除此之外,您可以在检索到的轮廓上应用各种条件,以便 filter/strengthen 您的分割。

但是,如果您的 detection/segmentation 需要的不仅仅是静态的,我强烈建议您将注意力转向基于机器学习的算法,但考虑到您感兴趣的对象远非普通对象,您将必须通过微调现有架构来使用您的自定义数据集进行训练。

总之,祝你好运!