需要帮助解决Python中裁剪图像的错误

问题描述 投票:0回答:1

我是 Python 新手,为了做作业,我编写了一个应该裁剪图像的函数。

当我尝试运行代码时,您收到一个错误,该错误指向我的代码中甚至找不到的行。

错误是

OSError:无法将模式 F 写入 JPEG

还有一个小问题。它迫使我接受

imagio.read
imageio.v2.read
的指挥,但我不知道为什么。

我们将不胜感激每一个帮助。非常感谢。

完整错误:

Traceback (most recent call last):
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\PIL\\JpegImagePlugin.py", line 650, in \_save
rawmode = RAWMODE\[im.mode\]
KeyError: 'F'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\\Users\\מחשב\\Desktop\\python\\עיבוד תמונה\\חיתוך.py", line 16, in \<module\>
imageio.v2.imwrite('crop_img.jpg', new_pic)
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\imageio\\v2.py", line 396, in imwrite
with imopen(uri, "wi", \*\*imopen_args) as file:
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\imageio\\core\\v3_plugin_api.py", line 367, in __exit__
self.close()
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\imageio\\plugins\\pillow.py", line 144, in close
self.\_flush_writer()
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\imageio\\plugins\\pillow.py", line 485, in \_flush_writer
primary_image.save(self.\_request.get_file(), \*\*self.save_args)
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\PIL\\Image.py", line 2439, in save
save_handler(self, fp, filename)
File "C:\\Users\\מחשב\\AppData\\Roaming\\Python\\Python310\\site-packages\\PIL\\JpegImagePlugin.py", line 653, in \_save
raise OSError(msg) from e
OSError: cannot write mode F as JPEG

我的代码是:

import numpy as np
import imageio

def pic_crop(img,height,dy,width,dx):
    new_img=np.zeros((dy,dx))
    for row in range(0,dy):
        for column in range(0,dx):
            new_img[row,column]=img[height+row,width+column]
return new_img

pic=imageio.v2.imread('myimageGR.jpg')
new_pic= pic_crop(pic,30,90,50,80)
print(new_pic.shape)
imageio.v2.imwrite('crop_img.jpg', new_pic)
python numpy error-handling crop python-imageio
1个回答
1
投票

new_img.dtype
float64
imageio.v2.imwrite
期望
uint8
为 jpeg 格式,所以要么这样做

new_img=np.zeros((dy,dx),dtype='uint8')

或者做

imageio.v2.imwrite('crop_img.jpg', new_pic.astype('uint8'))

你也可以简化

pic_crop
来避免这个问题

def pic_crop(img,height,dy,width,dx):
    new_img = np.array(img[height:height+dy, width:width+dx])
    return new_img
© www.soinside.com 2019 - 2024. All rights reserved.