python图像提取,从python中的图像中提取任意矩形块

Is there a way to extract a rectangle of my choice from an image, maybe using numpy arrays?

Most implementations available seem to be for regular sliding window solutions, but those always include steps, or rectangles of the same aspect ratio, or something like that.

Is it possible to provide the beginning x and y coordinates and the width and height (or ending x and y coordinates), and extract exactly that rectangle? Can this be done using numpy arrays alone? Or is there another way to do this?

解决方案

The best way to do this would be slicing i.e.

rect = np.copy(img[y1:y1+height,x1:x1+width])

where (x1, y1) is the upper left corner of your rectangle.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
从轮廓提取四个角点坐标的方法有很多,这里介绍一种基于cv2.convexHull()函数的方法。 1. 导入所需的库: ```python import cv2 import numpy as np ``` 2. 读取图像并进行灰度化和二值化处理: ```python img = cv2.imread('qrcode.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) ``` 3. 查找轮廓: ```python contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ``` 4. 对每个轮廓进行处理: ```python for cnt in contours: # 获取凸包 hull = cv2.convexHull(cnt) # 获取四个角点 points = cv2.boxPoints(cv2.minAreaRect(hull)) # 绘制四边形 cv2.drawContours(img, [points.astype(int)], -1, (0, 0, 255), 2) ``` 这里使用了 cv2.convexHull() 函数获取轮廓的凸包,然后使用 cv2.minAreaRect() 函数获取最小外接矩形,最后使用 cv2.boxPoints() 函数获取矩形的四个角点坐标。最后,使用 cv2.drawContours() 函数绘制四边形。 5. 显示图像: ```python cv2.imshow('contours', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这里使用了 cv2.imshow() 函数来显示图像,cv2.waitKey(0) 函数等待用户按下任意键后关闭窗口,cv2.destroyAllWindows() 函数用于关闭所有窗口。 完整代码如下: ```python import cv2 import numpy as np img = cv2.imread('qrcode.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: hull = cv2.convexHull(cnt) points = cv2.boxPoints(cv2.minAreaRect(hull)) cv2.drawContours(img, [points.astype(int)], -1, (0, 0, 255), 2) cv2.imshow('contours', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 执行完该代码后,您将会看到一个带有四个角点的四边形的图像

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值