给定从图像中裁剪ROI的(x,y,w,h)坐标,如何确保给定的坐标有效?例如:
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)坐标无效,它将引发以下错误:
错误: C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:350:错误:(-215:断言失败)函数'cv::imshow‘中的size.width>0 && size.height>0
我试图在裁剪ROI之前编写一个函数来验证坐标。目前,我的一些检查是为了确保:
(x,y,w,h)要么是int,要么是float,typex和y是>=,0w和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')发布于 2020-08-15 01:02:34
可以使用图像分辨率检查坐标是否在图像范围内:
# 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]https://stackoverflow.com/questions/63421624
复制相似问题