给定(x,y,w,h)
坐标以从图像中裁剪ROI,如何确保给定的坐标有效?例如:
image = cv2.imread('1.jpeg')
x,h = 0,300,300
ROI = image[y:y+h,x:x+w]
cv2.imshow('ROI',ROI)
cv2.waitKey()
如果(x,h)
坐标无效,则会引发此错误:
cv2。错误:OpenCV(4.0.0)C:\ projects \ opencv-python \ opencv \ modules \ highgui \ src \ window.cpp:350:错误:(-215:断言失败)size.width> 0 && size.height> 0在函数'cv :: imshow'
我正在尝试编写一个函数来在裁剪ROI之前验证坐标。目前,我的一些检查旨在确保:
-
(x,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,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,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,h):
return True
else:
return False
image = cv2.imread('1.jpeg')
print(image.shape)
x,h = 500,6600,300
coordinates = (x,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')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。