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

如何在python和opencv中移动ROI的顶点?,python,opencv,contour,roi,Python,Opencv,Contour,Roi,我试图在ROI中绘制轮廓。 但是ROI的顶点出现在图像的左侧。 我想将ROI移动到照片中指定的位置,但我不知道如何操作。 我是OpenCV和Python新手,非常感谢您的帮助。 这是我的密码 # Object detected center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * wi

我试图在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)


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

当您想要显示原始图像内部而不是ROI内部的轮廓时,您必须移动它们

基本上有两种选择:

  • 将您的ROI的
    x
    y
    传递给
    findContours
    like

    contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))
    
    cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))
    
    返回的
    等高线
    将具有相对于原始图像的坐标

  • x
    y
    传递到
    draw等高线

    contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))
    
    cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))
    
    这将保留相对于ROI的
    轮廓坐标
    ,并仅在原始图像内部显示它们

  • 什么对你有意义取决于你的应用程序

    第三个选项是手动移动轮廓,只需将
    x
    添加到第一个维度,将
    y
    添加到第二个维度。
    输出将与1相同。

    您的
    轮廓坐标
    框中。所以只需将它们移动
    x
    y
    ?不知道什么是
    很难说。谢谢您的评论。长方体是矩形的坐标。我编辑代码。请给我一些意见。只需按
    x
    y
    移动即可。试试看。我可以修改这个代码吗?“roi=img_二进制[y:y+h,x:x+w]”roi是正确的。你必须改变轮廓。有两种方法可以做到这一点。1.将
    x
    y
    作为最后一个参数(
    offset
    )传递给
    findContours
    。返回的
    等高线
    将具有相对于
    img\u二进制
    的坐标。或2。将
    x
    y
    作为
    offset
    传递到
    drawcours
    感谢您的友好回答。我已经运行了代码,它运行得非常好。