【问题标题】:How could crop the image using OpenCV or PIL?如何使用 OpenCV 或 PIL 裁剪图像?
【发布时间】:2019-03-26 06:36:44
【问题描述】:

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

【问题讨论】:

  • 我觉得this threadthis thread可以回答你的问题。
  • OpenCV 使用 (0,0) 位于左上角的坐标系。所以img[0:500, 0:500] 会在图片的左上角给你一个正方形。您需要知道起始 x 和 y,然后执行img[y:y+500, x:x+500] 之类的操作。例如,这个 x 和 y 可以是 x= 1080/2 -250y= 1920/2 -250 以获得一个居中的正方形。
  • ` x= 1080//2 - 250 y= 1920//2 - 250 img = img[y:y+500, x:x+500] `我得到img.size = (370, 500,3)。怎么样?
  • 您将row / colx / y 混淆了

标签: python image opencv


【解决方案1】:

试试这个:

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)

【讨论】:

  • 非常感谢您提供更好的想法。
猜你喜欢
  • 1970-01-01
  • 2012-04-16
  • 2018-12-11
  • 2012-10-01
  • 1970-01-01
  • 2013-03-06
  • 2012-12-22
  • 2012-12-31
  • 1970-01-01
相关资源
最近更新 更多