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

2024-05-15 15:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: keyin图像imageimportjsonforas
1条回答
网友
1楼 · 发布于 2024-05-15 15:33:43

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

相关问题 更多 >