-1

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
petezurich
  • 9,280
  • 9
  • 43
  • 57
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
  • 3
    I think [this thread](https://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python) and [this thread](https://stackoverflow.com/questions/9983263/crop-the-image-using-pil-in-python) can answer your question. – RomainTT Oct 22 '18 at 08:28
  • 1
    OpenCV uses a coordinate system that the (0,0) is on the top left. So `img[0:500, 0:500]` will get you a square in the top left of the image. You need to know the starting x and y and then do something like `img[y:y+500, x:x+500]`. This x and y could be for example, `x= 1080/2 -250` and `y= 1920/2 -250` to get a square centered in the middle. – api55 Oct 22 '18 at 08:32
  • ` x= 1080//2 - 250 y= 1920//2 - 250 img = img[y:y+500, x:x+500] ` I am getting `img.size = (370, 500,3)`. How? – Md. Rezwanul Haque Oct 22 '18 at 09:02
  • 2
    You confused the `row / col` with `x / y` – Hao Li Oct 22 '18 at 09:27

1 Answers1

2

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)
Hao Li
  • 1,593
  • 15
  • 27