简体   繁体   中英

How could crop the image using OpenCV or PIL?

The size of all images is (1080, 1920, 3) . I want to crop the image from right to left side like (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) .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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