Failed to read images when folder has special characters on name - python

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)

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 geotiff could not be opened by gdal?

I'm newbie in python and in geoprocessing. I'm writing some program to calculate ndwi. To make this, I try to open geotiff dataset with gdal, but dataset can't be opened. I tried to open different tiff files (Landsat8 multiple data, Landsat7 composite, etc), but dataset is always None.
What reason to this could be? Or how can i find it out?
Here's a part of code:
import sys, os, struct
import gdal, gdalconst
from gdalconst import *
import numpy as np
from numpy import *
class GDALCalcNDWI ():
def calcNDWI(self, outFilePath):
gdal.AllRegister()
# this allows GDAL to throw Python Exceptions
gdal.UseExceptions()
filePath = "C:\\Users\\Daria\\Desktop.TIF\\170028-2007-05-21.tif"
# Open
dataset = gdal.Open(filePath, gdal.GA_ReadOnly)
# Check
if dataset is None:
print ("can't open tiff file")
sys.exit(-1)
Thanks
Whenever you have a well-known file reader that is returning None, make sure the path to your file is correct. I doubt you have a directory called Desktop.TIF, I'm assuming you just made a typo in your source code. You probably want C:\\Users\\Dara\\Desktop\\TIF\\170028-2007-05-21.tif as the path (note that Desktop.TIF ==> Desktop\\TIF).
The safest thing to do is right click on the file, go to properties, and copy/paste that path into your python source code.

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.

Converting .jpg images to .png

I've looked around and read the docs, and found no way or solution, so I ask here. Is there any packages available to use Python to convert a JPG image to a PNG image?
You could always use the Python Image Library (PIL) for this purpose. There might be other packages/libraries too, but I've used this before to convert between formats.
This works with Python 2.7 under Windows (Python Imaging Library 1.1.7 for Python 2.7), I'm using it with 2.7.1 and 2.7.2
from PIL import Image
im = Image.open('Foto.jpg')
im.save('Foto.png')
Note your original question didn't mention the version of Python or the OS you are using. That may make a difference of course :)
Python Image Library: http://www.pythonware.com/products/pil/
From: http://effbot.org/imagingbook/image.htm
import Image
im = Image.open("file.png")
im.save("file.jpg", "JPEG")
save
im.save(outfile, options...)
im.save(outfile, format, options...)
Saves the image under the given filename. If format is omitted, the
format is determined from the filename extension, if possible. This
method returns None.
Keyword options can be used to provide additional instructions to the
writer. If a writer doesn't recognise an option, it is silently
ignored. The available options are described later in this handbook.
You can use a file object instead of a filename. In this case, you
must always specify the format. The file object must implement the
seek, tell, and write methods, and be opened in binary mode.
If the save fails, for some reason, the method will raise an exception
(usually an IOError exception). If this happens, the method may have
created the file, and may have written data to it. It's up to your
application to remove incomplete files, if necessary.
As I searched for a quick converter of files in a single directory, I wanted to share this short snippet that converts any file in the current directory into .png or whatever target you specify.
from PIL import Image
from os import listdir
from os.path import splitext
target_directory = '.'
target = '.png'
for file in listdir(target_directory):
filename, extension = splitext(file)
try:
if extension not in ['.py', target]:
im = Image.open(filename + extension)
im.save(filename + target)
except OSError:
print('Cannot convert %s' % file)
from glob import glob
import cv2
pngs = glob('./*.png')
for j in pngs:
img = cv2.imread(j)
cv2.imwrite(j[:-3] + 'jpg', img)
this url: https://gist.github.com/qingswu/1a58c9d66dfc0a6aaac45528bbe01b82
import cv2
image =cv2.imread("test_image.jpg", 1)
cv2.imwrite("test_image.png", image)
I don't use python myself, but try looking into:
http://www.pythonware.com/products/pil/
import Image
im = Image.open("infile.png")
im.save("outfile.jpg")
(taken from http://mail.python.org/pipermail/python-list/2001-April/700256.html )

Categories