Image moves or deletes when displaying with PIL - python

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')

Related

How am i able to save a picture using OpenCV imwrite to a specific folder

Im back with another probably stupid question!, my new issue is the following:
im trying to save a picture from my webcam into a specific folder using OpenCV imwrite,
its not working obviously here is my code:
import cv2 as cv
cam = cv.VideoCapture(0)
s, img = cam.read()
if s:
path = r"\imgtest\selfietest.jpg"
cv.imwrite(path, img)
Any suggestions for edits or fixes?, i've tried copying the file using shutil and moving it using the same module, i also tried to use the OS module to move it but it threw an "Access Denied" error so i would prefer to not need to grant the application admin rights every time i launched it thanks in advance!!
((ALSO ASSUME I KNOW NOTHING ABOUT PYTHON))
Use a full path, forward slashes, and r'' to pass a raw path. cv2.imwrite(r"D:/....jpg", img)

Failed to read images when folder has special characters on name

Basically I'm using locateOnScreen() function, which is from pyautogui to read an image and then find in the screen by:
import os
import pathlib
import pyautogui
Image = os.path.join(os.path.sep, pathlib.Path(__file__).parent.resolve(), 'static', 'img', 'game', 'image-btn.png')
if pyautogui.locateOnScreen(BossImg, grayscale=True, confidence=0.95) != None:
print(True)
The code above works prety fine, the problem is when some users, even me because my native language is Portuguese and we have special characters in the language, and we might have some in a folder name.
Let's use this example:
In english:
C:\Users\guilh\Desktop\Folder
In Portuguese:
C:\Users\guilh\Área de Trabalho\Folder
So for some cases when we get a folder with accented characters, I'm getting the error:
Failed to read C:\Users\guilh\Área de Trabalho\Folder\image-btn.png because file is missing, has improper permissions, or is an unsupported or invalid format
But why am I gettig this error with special characters if I'm passing the path correctly with pathlib and os? If I run the same script in the English example, works perfectly.
After digging a bit in the source code of PyAutoGUI on Github, it appears that PyScreeze is used to detect an element on the screen from an image of it, and it uses openCV's imread() function to load the image.
cv2.imread() currently does not support pathnames containing Non-ASCII characters on Windows.
A pull-request has already been opened on the PyScreeze repository to use cv2.imdecode() instead of cv2.imread().
To fix this issue while waiting for the support for non-ASCII characters,
Method 1
The first option would be to modify the PyScreeze package installed (This can be annoying if anyone needs to be able to run the script easily from their computer).
- Identify the location of the PyScreeze module:
python -c "import pyscreeze; print(pyscreeze.__path__)"
- Modify __init__.py located in this folder:
Line 21,
import numpy as np
Line 166,
img_cv = cv2.imdecode(np.fromfile(img, dtype=np.uint8), LOAD_GRAYSCALE)
Line 168,
img_cv = cv2.imdecode(np.fromfile(img, dtype=np.uint8), LOAD_COLOR)
- Finally install numpy
pip install numpy
Method 2
As #SiP explained, Another possibility could be to copy the image to a temporary folder.
Something like that:
import os
import pathlib
import tempfile
import shutil
import pyautogui
Image = os.path.join(os.path.sep, pathlib.Path(__file__).parent.resolve(), 'static', 'img', 'game', 'image-btn.png')
temp_path = os.path.join(tempfile.gettempdir(), "file_name_in_ascii")
shutil.copy2(Image, temp_path)
if pyautogui.locateOnScreen(temp_path, grayscale=True, confidence=0.95) is not None:
print(True)

(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>'

Python Pillow Image.show() Path Issue?

Honest warning—I'm a total beginner.
I'm using Python 3.8.2 in IDLE and sometimes in Spyder.
My goal: to open an image (located in a folder) in Preview using Pillow
My code:
from PIL import Image
my_image = Image.open("flower.jpg")
my_image.show(r"/Users/User/Desktop/flower.jpg")
I run this, and it works! But it only works if the jpg is on the Desktop. I want to put the image in a folder. So I changed my last line of code to something like this:
my_image.show(r"/Users/User/Desktop/folder/flower.jpg")
I put the image in the folder, run the program, and get this error:
**FileNotFoundError: [Errno 2] No such file or directory: 'flower.jpg'**
Oddly, if I put the jpg back onto the Desktop and still use the path with "folder" in it, the program runs successfully and shows me the image.
Is this a problem with the path? How can I use Image.show() to open an image that is located somewhere other than the Desktop?
Thank you!
If you want to open and view an image using an absolute path, you'll have to change this line:
my_image = Image.open(path_to_image_dir)
You've incorrectly passed a string to PIL.Image.show. This doesn't throw an error, since PIL.Image.show happens to take an optional string parameter title, which it will use as a title in the image window. Don't pass any parameters to show, and change "flower.jpg" in the line above to the actual path.

Reading image using Pillow fails in Jupyter notebook

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.

Categories