边界框选择整个图像而不是多边形



我正在尝试围绕多边形图像绘制边界框。我最初标记了图像,并使用json文件创建了多边形掩码。

这是我的代码:我使用json文件来保持文件名不变。

import cv2
import numpy as np
import json
import matplotlib.pyplot as plt
jsonFile ='/directory..../.json' 
with open(jsonFile) as file:
annotations = json.load(file)

for key in annotations:
regions = annotations[key]['regions']
for region in regions:
print(annotations[key]['filename'],"n")
image = cv2.imread('/directory to mask images.png' + annotations[key]['filename'])
original = image.copy()
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0,255,cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find contours, obtain bounding box, extract and save ROI
ROI_number = 0
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]
cv2.imwrite('ROI_{}.png'.format(annotations[key]['filename']), ROI)
ROI_number += 1
cv2.imshow('image', image)
cv2.waitKey()

我的问题是,我只是勾勒出完整图像的边界,而不是在图片中的多边形上绘制边界框。

如果重要的话,图像是黑色的,多边形遮罩是白色的。

我认为问题可能来自阈值操作。如果原始图像是带白色多边形的黑色图像,则cv2.THRESH_BINARY_INV会将其转换为带黑色多边形的白色图像。由于轮廓函数找到围绕空白的多边形,因此生成的多边形将围绕整个图像。为了解决此问题,只需使用cv2.THRESH_BINARY而不是cv2.THRESH_BINARY_INV

最新更新