裁剪图像后无法调用 .show() 函数

问题描述

我试图在此处裁剪图像,但是每次在裁剪后的图像上运行 .show() 时,它都会给我一个错误

使用 Python 3.9.1 和 Pillow 8.0

from PIL import Image
image = Image.open('image.PNG')
print (image.size)
width,height = image.size

print (width)
print (height)

newWidth = int(width/2)
newHeight = int(height/2)

print (newWidth)
print (newHeight)

img = image.crop((newWidth,newHeight,newWidth,newHeight))

img.show()

这是错误的样子

Error Code

解决方法

使用 cv2 的替代方法

import cv2
img=cv2.imread("image.PNG")
new_height=int(img.shape[0]/2)
new_width=int(img.shape[1]/2)
img=img[0:new_height,0:new_width] #cropping image
cv2.imshow("cropped_image",img)
cv2.waitKey(0)
,

如果您想剪切图像的中心,那一定会有所帮助。问题出在 CROP 函数的参数中。你应该用新图像的角坐标来填充它。写英文对我来说很难,所以如果你不明白什么可以问我

from PIL import Image

image = Image.open(r'image.png')
print(image.size)
width,height = image.size

print(width)
print(height)

newWidth = int(width / 2)
newHeight = int(height / 2)

print(newWidth)
print(newHeight)

left = width - newWidth // 2
upper = height - newHeight // 2
right = left + newWidth
lower = upper + newHeight

img = image.crop((left,upper,right,lower))

img.show()