给定(x,y,w,h)
坐标以从图像中裁剪ROI,如何确保给定的坐标有效?例如:
image = cv2.imread('1.jpeg')
x,y,w,h = 0,0,300,300
ROI = image[y:y+h,x:x+w]
cv2.imshow('ROI', ROI)
cv2.waitKey()
如果(x,y,w,h)
坐标无效,则会引发此错误:cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:350: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
我正在尝试编写一个函数来在裁剪ROI之前验证坐标。目前,我的一些检查旨在确保:
(x,y,w,h)
都是int
或float
类型x
和y
> = 0 w
和h
> 0 有时仍然会引发错误,我缺少哪些检查?
示例图片:
码:
import cv2
def validate_ROI_coordinates(coordinates):
# (x,y) is top left coordinates
# Top right corner is is (x + w)
# Bottom left corner is (y + h)
x,y,w,h = coordinates
# Ensure its a number, not boolean or string type
def int_or_float(s):
try:
i = int(s)
return True
except ValueError:
try:
f = float(s)
return True
except:
return False
def within_bounds(x,y,w,h):
# Ensure that x and y are >= 0
if x >= 0 and y >= 0:
# Ensure w and h are > 0 ( can be any positive number)
if w > 0 and h > 0:
return True
else:
return False
if all(int_or_float(value) for value in coordinates) and within_bounds(x,y,w,h):
return True
else:
return False
image = cv2.imread('1.jpeg')
print(image.shape)
x,y,w,h = 500,0,6600,300
coordinates = (x,y,w,h)
if validate_ROI_coordinates(coordinates):
ROI = image[y:y+h,x:x+w]
cv2.imshow('ROI', ROI)
cv2.waitKey()
else:
print('Invalid ROI coordinates')
最佳答案
您可以使用图像分辨率检查坐标是否在图像范围内:
# get resolution and coordinates
height, width = image.shape[:-1]
xmin, ymin, w, h = coordinates
xmax = xmin + w
ymax = ymin + h
# fetch roi
if (xmin >= 0) and (ymin >= 0) and (xmax < width) and (ymax < height):
roi = image[ymin:ymax, xmin:xmax]
关于python - 确保ROI裁剪坐标(x,y,w,h)有效且在Python OpenCV的范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63421624/