python opencv创建ROI并将ROI裁剪
时间: 2024-06-15 11:06:05 浏览: 180
OpenCV图像ROI裁剪
以下是两种Python使用OpenCV创建ROI并将ROI裁剪的例子:
1. 使用cv2.selectROI函数创建ROI并裁剪[^1]:
```python
import cv2
src = cv2.imread("F:\\Image\\Image.bmp", 1)
proimage0 = src.copy()
# 创建ROI
roi = cv2.selectROI(windowName="roi", img=src, showCrosshair=False, fromCenter=False)
x, y, w, h = roi
# 在图像上绘制ROI矩形框
cv2.rectangle(img=src, pt1=(x, y), pt2=(x + w, y + h), color=(0, 0, 255), thickness=2)
# 显示ROI和裁剪后的图像
cv2.imshow("roi", src)
ImageROI = proimage0[y:y+h, x:x+w]
cv2.imshow("ImageROI", ImageROI)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 直接裁剪图片[^2]:
```python
import cv2
img = cv2.imread("F:\\Image\\Image.bmp", 1)
# 裁剪ROI
width = img.shape[0]
height = img.shape[1]
img = img[int(0.5 * height):height, 0:width]
# 显示裁剪后的图像
cv2.imshow("ImageROI", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文