如何在 python 和 opencv 中移动 ROI 的顶点?
How can i move the vertices of the ROI in python and opencv?
我试图在 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 的。
IE。 x
轮廓的坐标是相对于 ROI 的左上角的。 y
.
相同
由于您想要显示原始图像内部的轮廓而不是 ROI 内部的轮廓,因此您必须移动它们。
基本上有两种选择:
将您的投资回报率 x
和 y
传递给 findContours
喜欢
contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))
返回的 contours
将具有相对于原始图像的坐标。
将x
和y
传递给drawContours
喜欢
cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))
这将保留您的 contours
相对于 ROI 的坐标,并将它们显示在原始图像内部。
什么对你有意义取决于你的应用程序。
第三个选项是通过简单地将 x
添加到第一个维度并将 y
添加到第二个维度来手动移动轮廓。
输出将与 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)
返回的轮廓坐标是相对于传递给 findContours
的 ROI 的。
IE。 x
轮廓的坐标是相对于 ROI 的左上角的。 y
.
由于您想要显示原始图像内部的轮廓而不是 ROI 内部的轮廓,因此您必须移动它们。
基本上有两种选择:
将您的投资回报率
x
和y
传递给findContours
喜欢contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))
返回的
contours
将具有相对于原始图像的坐标。将
x
和y
传递给drawContours
喜欢cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))
这将保留您的
contours
相对于 ROI 的坐标,并将它们显示在原始图像内部。
什么对你有意义取决于你的应用程序。
第三个选项是通过简单地将 x
添加到第一个维度并将 y
添加到第二个维度来手动移动轮廓。
输出将与 1 相同。