【问题标题】:Resize the images crop the exceeding part调整图像大小裁剪超出部分
【发布时间】:2021-10-07 11:18:59
【问题描述】:

我有一个分辨率为1221 x 821 的图像,如果部分超出此范围,我想将其调整为1200 x 800,只需裁剪它即可。此外,我想保留中间部分。怎么可能?

【问题讨论】:

  • 如果你打算批量做深度学习,可以考虑使用torchvision.transforms.CentreCrop
  • 顺便说一句,不用写任何Python也可以做到。只需在终端 magick INPUT.PNG -gravity center -crop 1200x800+0+0 +repage RESULT.PNG 中使用 ImageMagick

标签: python image crop


【解决方案1】:

您可以简单地使用opencv

import cv2

img = cv2.imread(<>) # 1221 x 821

top=0 # Crop from top
buttom=821 # Crop from buttom
left=0 # Crop from left
right=1221 # Crop from right

cropped_image = img[top:buttom,left:right] # 1221 x 821

cv2.imwrite(cropped_image,<file name>)

或者使用PIL

from PIL import Image

im = Image.open(<>) # 1221 x 821

left=0 # Crop from left
top=0 # Crop from top
right=1221 # Crop from right
buttom=821 # Crop from buttom

im1 = im.crop((left, top, right, bottom)) # 1221 x 821

im1 = im1.save(<>)

有关它的更多信息,请访问here

如果你想获取图片的宽度和高度,那么opencv

dimensions = img.shape

img.shape 返回(高度、宽度、通道数)

高度表示图像中的像素行数或图像数组每列中的像素数。

宽度表示图像中的像素列数或图像数组每行的像素数。

并使用PIL

width, height = im.size

size 是一个 (width, height) 元组

【讨论】:

  • 不是该函数必须知道需要裁剪的特定区域,但在我的函数中,我想每次调整不同图像的大小并且不想测量左、右、上,每次底部尺寸
  • 如果我想将图像从 800x450 裁剪到 800x448,我应该输入什么?因为我现在处于 SystemError: tile cannot extend outside image
  • @MoJiebu 我已经给你添加了完整的描述,相信你现在会明白的。如何使用这些!如果您仍然感到困惑,请尝试使用这些值,增加减少,这样做您会更好地理解。
  • @MoJiebu 如果你喜欢我的努力,你也可以点赞。 :)
猜你喜欢
  • 2011-11-11
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多