简体   繁体   English

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

[英]How could crop the image using OpenCV or PIL?

The size of all images is (1080, 1920, 3) .所有图像的大小为(1080, 1920, 3) I want to crop the image from right to left side like (500, 500, 3) .我想从右到左裁剪图像,如(500, 500, 3) I've tried with follwing code:我试过以下代码:

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

As far as I know it work from left to right.据我所知,它从左到右工作。 And also need crop middle of the portion that called ROI and it'll size also (500, 500, 3) .并且还需要称为ROI的部分的中间进行裁剪,并且它的大小也会是(500, 500, 3)

How can do these work?这些工作怎么做?

->(Q.1)

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

->(Q.2)

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

Try this:尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM