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

时间:2018-10-22 08:23:32

标签: python image opencv

所有图像的大小为(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

1 个答案:

答案 0 :(得分:2)

尝试一下:

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)