我如何在python和opencv中移动ROI的顶点?

问题描述 投票:0回答:1

我试图在ROI中绘制轮廓。但是,ROI的顶点显示在图像的左侧。我想将ROI移到照片中指示的位置,但是我不知道该怎么做。我是OpenCV和Python的新手,所以非常感谢您的帮助。这是我的代码。

“在此处输入图像描述”

# Object detected
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)
            # Rectangle coordinates
            x = int(center_x - w / 2)
            y = int(center_y - h / 2)
            boxes.append([x, y, w, h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.4, 0.3)

for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        confidence = confidences[i]
        color = colors[class_ids[i]]

        img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        ret, img_binary = cv2.threshold(img_gray, 15, 255, 0)
        roi = img_binary[y:y+h, x:x+w]
        contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(frame, contours, -1, (0,255,0), 3)
        print(roi.shape)
        print(x, y, w, h)
python opencv contour roi
1个回答
0
投票

返回的轮廓坐标相对于传递给findContours的ROI。即轮廓的x坐标相对于ROI的左上角。与y相同。

由于要在原始图像内而不是在ROI内显示轮廓,因此必须移动它们。

基本上有两个选择:

  1. 将ROI的xy传递给findContours,例如

    contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))
    

    返回的contours将具有相对于原始图像的坐标。

  2. xy传递到drawContours,例如

    cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))
    

    这将保留contours相对于ROI的坐标,仅将它们显示在原始图像内。

什么对您有意义取决于您的应用程序。

[第三个选项是通过简单地将x添加到第一维,并将y添加到第二维来手动移动轮廓。输出将与1相同。

© www.soinside.com 2019 - 2024. All rights reserved.