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()
我的问题不是在图片中的多边形上绘制边界框,而是勾勒出整个图像的边框。
如果重要,图像是黑色的,多边形蒙版是白色的。
解决方案
我认为问题可能来自阈值操作。如果原始图像是带有白色多边形的黑色图像,则将其cv2.THRESH_BINARY_INV
转换为带有黑色多边形的白色图像。由于轮廓函数会找到围绕空白区域的多边形,因此生成的多边形将围绕整个图像。为了解决这个问题,只需使用cv2.THRESH_BINARY
而不是cv2.THRESH_BINARY_INV
.
推荐阅读
- linux - 如何在提交前从 git add 中删除某种类型的文件和目录?
- c++ - 以 .(dot) 为前缀的结构变量名称需要解释
- node.js - 如何使用 nock 库模拟连接?
- javascript - JavaScript:如何将参数传递给最终将被删除的侦听器函数
- reactjs - 如何在 cache.readQuery 或 cache.writeQuery 中使用 this.state.rent 值而不是 this.props.house.rent 值
- javascript - 在 php 页面中为 html 内容创建搜索功能
- javascript - 在 forEach 循环中分配给类变量 - 没有结果?
- java - 使用 C# SOAP 序列化程序的 RSA 两因素身份验证
- java - TaskRejectedException 抛出和线程池未满
- google-apps-script - 类似的 OnEdit 和 OnEdit2 脚本不能一起工作