首页 > 解决方案 > 边界框选择整个图像而不是多边形

问题描述

我正在尝试在多边形图像周围绘制边界框。我最初标记了图像并使用 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()

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

如果重要,图像是黑色的,多边形蒙版是白色的。

标签: pythonmaskcv2bounding-box

解决方案


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


推荐阅读