python - 如何使用 Python 沿着带有矩形边界框的斑点/轮廓的主轴裁剪图像
问题描述
我想裁剪一个带有手绘橙色突出显示区域的图像,如下所示,
结果应该是沿着斑点或轮廓的长轴裁剪的图像,带有矩形边界框,如下所示,
这是我尝试过的,
import numpy as np
import cv2
# load the image
image = cv2.imread("frame50.jpg", 1)
#color boundaries [B, G, R]
lower = [0, 3, 30]
upper = [30, 117, 253]
# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask=mask)
ret,thresh = cv2.threshold(mask, 50, 255, 0)
if (int(cv2.__version__[0]) > 3):
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
else:
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if len(contours) != 0:
# find the biggest countour (c) by the area
c = max(contours, key = cv2.contourArea)
x,y,w,h = cv2.boundingRect(c)
ROI = image[y:y+h, x:x+w]
cv2.imshow('ROI',ROI)
cv2.imwrite('ROI.png',ROI)
cv2.waitKey(0)
这似乎在大多数情况下都不起作用。对于某些图像,会发生以下情况,
我想知道是否有更好的方法来解决这个问题,或者我如何修复我现在拥有的东西。请注意,突出显示的区域是手绘的,可以是任何形状,但它是封闭的,不能保持打开状态,颜色在所有情况下,亮点是橙色本身的阴影。有没有办法只保留圈内的内容而将圈外的所有内容都涂黑?
EDIT1: 我能够通过更多地改变阈值来修复错误的剪辑。但我现在的主要疑问是:有没有办法只保留圈内的内容而将圈外的所有内容都涂黑?我可以看到如下所示的面具,
如何使用相同的矩形边界框填充此蒙版并保留圆圈内的内容并将其外的所有内容涂黑?
解决方案
你有没有尝试过
image[x:x+w, y:y+h]
你能用下面的代码检查 bbox
cv2.rectangle(thresh,(x,y),(x+w,y+h),(255,0,0),2)
推荐阅读
- node.js - 快递:如何结束回复
- batch-file - 如何将带有特殊字符的参数从 vbs 传递到批处理文件而不用双引号括起来?
- typescript - TS2339:联合类型上不存在属性 - 属性字符串 | 不明确的
- java - 列的值太长 - 错误持续存在 LocalDate
- memory-leaks - 如何查看单声道 MLPD 文件以进行分析
- go - 为 golang 运行 GRPC 示例
- jenkins - 监控 Jenkins 节点上的特定磁盘空间
- python - Python 使用 Py 文件发送包
- csv - 如何将“.csv”数据文件导入 Redis 数据库
- elasticsearch - ansible弹性搜索安装版本不匹配失败