如何使用OpenCV或PIL裁剪图像?

2024-04-27 02:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

所有图像的大小都是(1080, 1920, 3)。我想像(500, 500, 3)那样从右到左裁剪图像。我试过以下代码:

img = img[0:500, 0:500] #y, x

据我所知,它是从左到右工作的。也需要裁剪中间的部分,叫做ROI,它的大小也会(500, 500, 3)。你知道吗

你怎么能做这些工作?你知道吗

->(Q.1)

1920
--------------
|            |
|     500    |
|     -------|  
|     |      |
|     |      | 
|     -------|500
|     0      |
|            |
--------------
0            1080

->(Q.2)

    1920
--------------
|            |
|     500    |
|  -------   |
|  |     |   |
|  |     |   |
|  -------500|
|     0      |
|            |
--------------
0            1080

Tags: 代码图像imgroi
1条回答
网友
1楼 · 发布于 2024-04-27 02:59:53

试试这个:

import numpy as np
import cv2


def crop(img, roi_xyxy, copy=False):
    if copy:
        return img[roi_xyxy[1]:roi_xyxy[3], roi_xyxy[0]:roi_xyxy[2]].copy()
    return img[roi_xyxy[1]:roi_xyxy[3], roi_xyxy[0]:roi_xyxy[2]]

img = np.random.randint(0, 255, (1080, 1920, 3), dtype=np.uint8)
row, col, _ = img.shape
img[row // 2, :] = 255
img[:, col // 2] = 255
cv2.imshow("img", img)

roi_w, roi_h = 500, 500
# roi_w, roi_h = 500, 200
cropped_img = crop(img, (col//2 - roi_w//2, row//2 - roi_h//2, col//2 + roi_w//2, row//2 + roi_h//2))
print(cropped_img.shape)
cv2.imshow("cropped_img", cropped_img)
cv2.waitKey(0)

相关问题 更多 >