I'm new to Python and for homework, I wrote a function that supposed to crop a image.
When I try to run the code u get an error that points to line that isn't even found in my code.
The error is
OSError: cannot write mode F as JPEG
Also another little question. it force me to put in the command of imagio.read
, imageio.v2.read
and I don't know why.
Every help will be appreciated. Thank you very much.
Full error:
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
My code is:
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)
new_img.dtype
is float64
, imageio.v2.imwrite
expects uint8
for jpeg format, so either do
new_img=np.zeros((dy,dx),dtype='uint8')
or do
imageio.v2.imwrite('crop_img.jpg', new_pic.astype('uint8'))
also you can simplify pic_crop
to avoid this problem
def pic_crop(img,height,dy,width,dx):
new_img = np.array(img[height:height+dy, width:width+dx])
return new_img