Reading image using Pillow fails in Jupyter notebook - python

I'm trying to read a jpg file using Pillow (Version 3.2.0) in Jupyter notebook (Python 3.4), but it fails with the following error:
OSError: broken data stream when reading image file
I'm using the following code:
from PIL import Image
im = Image.open("/path/to/image.jpeg")
im.show()
It works fine both in the interactive Python shell and using Python 2.7 instead of 3.4.
I've followed these steps already: Using Pillow with Python 3
Anyone an idea what's going on?

Looks like you're not pointing to the directory where your photo is stored.
import os
defaultWd = os.getcwd()
defaultWd # Sets your curretn wd
os.chdir(defaultWd + '\\Desktop') # Points to your photo--e.g., on Desktop
os.getcwd() # Shows change in wd
from PIL import Image
im = Image.open("Mew.jpg")
im.show() # Will plot to your default image viewing software
And another way if you don't want to change current wd:
im = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
im.show()
And if you want to plot inline:
from matplotlib.pyplot import imshow
%matplotlib inline
inlinePic = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
imshow(inlinePic)
Note: You may also want to simply try typing 'jpg' instead of 'jpeg' as you did above, if your image is in your current working directory. Also, if PIC is not installed, you'll get this error NameError: name 'Image' is not defined.

The problem was related to another import: I was importing Tensorflow before PIL, which caused the problem. Same issue as this one: https://github.com/scikit-image/scikit-image/issues/2000. Changing the order of the imports solved it.

Related

Image moves or deletes when displaying with PIL

Recently, I have been working on one of my python3 programs and then I wanted to to open a picture. Here is the code that I used to do it:
from PIL import Image
r = Image.open('C:/Users/sudam/OneDrive/Desktop/programming/python/projects/good night app/morning.png' )
r.show()
But as soon as I run this code,the windows photo viewer opens and gives and error saying that the specified file was moved. I tried googling this question but all of the answers I got only worked for python2, but not for python3.
Because you have whitespace in your path you need to use the r"string" format.
Also you need to use:
PIL.ImageShow.show(r)
to show your image.
It's also recommended to check if the file exist before opening any file.
You can do like this:
from pathlib import Path
from PIL import Image, ImageShow
path =r"C:/Users/sudam/OneDrive/Desktop/programming/python/projects/good night app/morning.png"
if Path(path).is_file():
r = Image.open(path)
ImageShow.show(r)
else:
print(f'{path} not exist')

(Python) Tesseract Installation Problem in Windows

I've read a couple other answers on this, but I'm still stuck. I imagine I'm doing something stupid, but this doesn't work:
import pytesseract
from PIL import Image
def tryTesseract(u):
return(pytesseract.image_to_string(Image.open(u)))
loc = 'C:\\Python\\Lineups\\558.png'
print(pytesseract)
print(tryTesseract(loc))
The first line prints:
<module 'pytesseract' from 'C:\Python\lib\site-packages\pytesseract\init.py'>
But the second prints several lines of error and culminates in:
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.
This seems weird if the first line works. I BELIEVE I have correctly added it to path though, and it is correctly installed, as in this screenshot:
Full error message:
Edited for exciting new error. I followed user3250052's advice and am now getting a new error (CMD window on top of Python window here:)
from PIL import Image
def tryTesseract(u):
return(pytesseract.image_to_string(Image.open(u)))
loc = os.path.join('C','Python','Lineups','558.png')
pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR'
print(pytesseract)
print(tryTesseract(loc))```
That is a file not fond error.
Try
loc = os.path.join('C','Python','Lineups','558.png')
you might also need
pytesseract.tesseract_cmdloc = r'<full_path_to_your_tesseract_executable>'

Why openCV is "blocking" my python script?

so I am still new to python and I tried to use a script that create bokeh effect on an image written by someone else. Here is the repository : Bokeh-Effect-in-Image-using-Python
Here is more information about how the code works from the author: bokeh-effect-in-image-using-python
Notice that I am coding on VSCode, macOS BigSur, Python 3.9.
First I created a folder for my project then I created a virtual environment, it has been recognised by VsCode and incorporated into the project (so I have the .vscode folder with the json file), I created a python file in which I pasted the code and I downloaded the packages I needed inside the virtual environment.
I also tried to add different lines in the json file based on what I read on the web but it doesn't work.
The problem is that the code runs until it encounters lines using OpenCV package, I don't have any Traceback but the code just do nothing.
Here is what I have in the terminal.
Terminal
I tried to use print at different places and to remove certain lines which use opencv and the problem occurred each time opencv was used or when Tracker_HSV was used (if I deleted all the lines using opencv before) but I think it is because Tracker_HSV use OpenCV.
So maybe I made a mistake during the setup of the project or opencv is not working correctly, I don't know what to do.
(Sorry for my English, I am French.)
According to the information you provided, for the use of the module "opencv", it is recommended that you try the following:
Please install the module "opencv" correctly: "pip install opencv-python"
Please use the absolute path of the picture in the code here: "img = cv.imread("D:/.../Bokeh_Demo/flower.jpg")"
When importing the module "cv2", because it contains other files named "cv2", (so pylint reported some errors here, but this does not affect the execution of the code). We can use "from cv2 import cv2 as cv" to distinguish them.
Run:
Update 1:
Please check that the module "opencv" has been successfully installed in your currently selected VSCode environment:
More reference: Environment in VSCode.
Update 2:
# import cv2
from cv2 import cv2 as cv
import numpy as np
import Tracker_HSV as tr
from PIL import Image
import os
# cv2.namedWindow('mask', cv2.WINDOW_NORMAL)
cv.namedWindow('mask',cv.WINDOW_NORMAL)
cv.resizeWindow('mask',(500,500))
filename= 'flower.jpg'
cwd = os.getcwd()
name_file=os.path.splitext(filename)[0]
path_save_temp=os.path.join(cwd,'Data')
path_save_folder=os.path.join(path_save_temp,f'{name_file}_blur_data')
if not os.path.exists(path_save_folder):
os.makedirs(path_save_folder)
img = cv.imread("D:/....../test_Bokeh/Bokeh_Demo/flower.jpg")
blur = cv.GaussianBlur(img,(5,5),0)
img_hsv=cv.cvtColor(img,cv.COLOR_BGR2HSV)
file_save_blur= os.path.join(path_save_folder,'blur.png')
im_blur = cv.GaussianBlur(img,(81,81),0)
cv.imwrite(file_save_blur,im_blur)
xs,ys,w,h = cv.selectROI('mask',img)
crop_img=crop_img_true=crop_img_contour=img[ys:ys+h, xs:xs+w]
if not crop_img_true.shape[0]> 1:
crop_img_true=img
x,y,z,a,b,c=(tr.tracker(crop_img_true))
crop_img_true=cv.cvtColor(crop_img_true,cv.COLOR_BGR2HSV)
file_save_mask_inrange= os.path.join(path_save_folder,'mask inRange.png')
mask_inRange=cv.inRange(crop_img_true,(x,y,z),(a,b,c))
cv.imwrite(file_save_mask_inrange,mask_inRange)
_, threshold = cv.threshold(mask_inRange, 250, 255, cv.THRESH_BINARY)
Gauss_threshold =cv.adaptiveThreshold(threshold,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY_INV,101,10)
blank_space_black= np.zeros((crop_img_true.shape[0],crop_img_true.shape[1]),np.uint8)
blank_space_black[:]=(0)
_,contours,_ = cv.findContours(Gauss_threshold, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
maxi=cv.contourArea(contours[0])
c=[]
for cnt in contours:
if cv.contourArea(cnt)>=maxi:
maxi=cv.contourArea(cnt)
## print(cv2.contourArea(cnt))
c= cnt
file_save_contour= os.path.join(path_save_folder,'Contour.png')
cv.drawContours(crop_img_contour, c, -1, (0, 255, 0), 5)
cv.imwrite(file_save_contour,crop_img_contour)
file_save_poly= os.path.join(path_save_folder,'mask fill poly.png')
mask_poly=cv.fillConvexPoly(blank_space_black,c,(255,255,255))
cv.imwrite(file_save_poly,mask_poly)
crop_img_true=cv.cvtColor(crop_img_true,cv.COLOR_HSV2BGR)
file_save_mask_bitwise= os.path.join(path_save_folder,'mask bitwise and.png')
mask_bitwise_and = cv.bitwise_and(crop_img_true,crop_img_true,mask=mask_poly)
cv.imwrite(file_save_mask_bitwise,mask_bitwise_and)
im2= Image.open(file_save_mask_bitwise)
im2=im2.convert('RGBA')
datas=im2.getdata()
newdata=[]
for data in datas:
if data[0]== 0 and data[1]== 0 and data[2]== 0:
newdata.append((255,255,255,0))
else:
newdata.append(data)
file_save_transparent= os.path.join(path_save_folder,'transparent.png')
im2.putdata(newdata)
im2.save(file_save_transparent)
im_blur= Image.open(file_save_blur)
file_save_final= os.path.join(path_save_folder,'final.png')
im_blur.paste(im2,(xs,ys),im2)
im_blur.save(file_save_final)
im_final= Image.open(file_save_final)
im_final.show('Final Result')
cv.imshow('GaussianBlur',blur)
cv.waitKey(0)
cv.destroyAllWindows()

Using MemoryFS file-like object with PIL Image

I'm trying to open Image file from PyFileSystem MemoryFS using PIL, I tried to do that like this example and i got the error below:
from PIL import Image
from fs.memoryfs import MemoryFS
fs=MemoryFS()
fs.makedir("test")
out=fs.open("test/file.jpg",'wb')
out.write(someimagefile.read())
out.close()
in=fs.open("test/file.jpg",'rb')
im=Image.open(in) #error: cannot identify image file <IO wrapper for <MemoryFile in <MemoryFS> test/file.jpg>>
however if I don't use a directory (ex. out=fs.open("file.jpg",'wb')) It does work as expected.
What am I doing wrong?
Thanks for your help.
I already get an error using the following line:
from fs.memoryfs import MemoryFS
Probably I don't have that library installed. Do you need this library? You can just open the image without opening it with MemoryFS:
im = Image.open("test/file.jpg")
Side note: I wouldn't use in as variable name, since it is also a Python keyword.

Python PIL Paste

I want to paste a bunch of images together with PIL. For some reason, when I run the line blank.paste(img,(i*128,j*128)) I get the following error: ValueError: cannot determine region size; use 4-item box
I tried messing with it and using a tuple with 4 elements like it said (ex. (128,128,128,128)) but it gives me this error: SystemError: new style getargs format but argument is not a tuple
Each image is 128x and has a naming style of "x_y.png" where x and y are from 0 to 39. My code is below.
from PIL import Image
loc = 'top right/'
blank = Image.new("RGB", (6000,6000), "white")
for x in range(40):
for y in reversed(range(40)):
file = str(x)+'_'+str(y)+'.png'
img = open(loc+file)
blank.paste(img,(x*128,y*128))
blank.save('top right.png')
How can I get this to work?
This worked for me, I'm using Odoo v9 and I have pillow 4.0.
I did it steps in my server with ubuntu:
# pip uninstall pillow
# pip install Pillow==3.4.2
# /etc/init.d/odoo restart
You're not loading the image correctly. The built-in function open just opens a new file descriptor. To load an image with PIL, use Image.open instead:
from PIL import Image
im = Image.open("bride.jpg") # open the file and "load" the image in one statement
If you have a reason to use the built-in open, then do something like this:
fin = open("bride.jpg") # open the file
img = Image.open(fin) # "load" the image from the opened file
With PIL, "loading" an image means reading the image header. PIL is lazy, so it doesn't load the actual image data until it needs to.
Also, consider using os.path.join instead of string concatenation.
For me the methods above didn't work.
After checking image.py I found that image.paste(color) needs one more argument like image.paste(color, mask=original). It worked well for me by changing it to this:
image.paste(color, box=(0, 0) + original.size)

Categories