首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >确保ROI裁剪坐标(x,y,w,h)是有效的,并且在Python OpenCV的范围内

确保ROI裁剪坐标(x,y,w,h)是有效的,并且在Python OpenCV的范围内
EN

Stack Overflow用户
提问于 2020-08-15 00:54:43
回答 1查看 1.6K关注 0票数 0

给定从图像中裁剪ROI的(x,y,w,h)坐标,如何确保给定的坐标有效?例如:

代码语言:javascript
复制
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之前编写一个函数来验证坐标。目前,我的一些检查是为了确保:

  1. (x,y,w,h)要么是int,要么是float,type
  2. xy是>=,0
  3. wh是> 0

有时它仍然会抛出错误,我遗漏了哪些检查?

示例图像:

代码:

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

发布于 2020-08-15 01:02:34

可以使用图像分辨率检查坐标是否在图像范围内:

代码语言:javascript
复制
# 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]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63421624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档