Unable to open an image through PIL in googlecolab - python-3.x

!wget https://github.com/lazyprogrammer/machine_learning_examples/blob/master/cnn_class/lena.png
from PIL import Image
im =Image.open('lena.png')
UnidentifiedImageError Traceback (most recent call last)
in ()
----> 1 im =Image.open('lena.png')
/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode)
2929 warnings.warn(message)
2930 raise UnidentifiedImageError(
-> 2931 "cannot identify image file %r" % (filename if filename else fp)
2932 )
2933
UnidentifiedImageError: cannot identify image file 'lena.png'

The link you are using to wget is all wrong. You are actually sending a GET request to the html file instead of the image.
Here's the actual image link for you :)
https://raw.githubusercontent.com/lazyprogrammer/machine_learning_examples/master/cnn_class/lena.png

Related

How can use Image.open("image.png") on Google Colab?

I was trying to convert an image to text, I execute this code on Google Colab, I think, I have a problem with the path of a file, maybe, so, please help to get a solution to this code. How can I get a solution?
from PIL import Image
import pytesseract
# Open the temporary file using PIL
image = Image.open("image.png")
# Use the Tesseract OCR engine to extract the text
text = pytesseract.image_to_string(image, lang = 'eng', config='--psm 11')
# Print the extracted text
print(text)
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-63-86a0a5214b2a> in <module>
4
5 # Open the temporary file using PIL
----> 6 image = Image.open("image.png")
7
8 # Use the Tesseract OCR engine to extract the text
/usr/local/lib/python3.8/dist-packages/PIL/Image.py in open(fp, mode)
2841 # Abstract handlers.
2842
-> 2843
2844 class ImagePointHandler:
2845 """
FileNotFoundError: [Errno 2] No such file or directory: 'image.png'
I got this error when I execute. How can I get a solution to image = Image.open("image.png")?

Python can properly be executed in IDEA, but when executing the executable file, following error appears: ModuleNotFoundError: No module named 'PIL'

I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Here is my code:
import shutil
from PIL import Image
import glob, os
import time
output_directory = "./Output"
def photo_picker():
pictures = []
try:
for filename in glob.iglob("./Input/*.jpg"):
pictures.append(filename)
except FileNotFoundError:
print("could not execute")
return pictures
def create_output_folder():
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
try:
os.mkdir(path=output_directory, mode=777)
except FileExistsError:
print("Could not execute")
def crop_image(img, new_name):
size = (2000, 2000)
with Image.open(img) as im:
im.thumbnail(size)
print(im.info)
img_name = f"{new_name}"
im.save(output_directory + "/" + img_name, "JPEG")
def main():
photos = photo_picker()
create_output_folder()
time.sleep(2)
for f in photos:
img_name_splitted = f.split("/")
img_name = img_name_splitted[len(img_name_splitted) - 1]
print(img_name)
crop_image(f, img_name)
return 0
if __name__ == "__main__":
main()
I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.

PIL.UnidentifiedImageError: cannot identify image file

I'm working on GCP cloud functions and intend to write a functions which combines two images. But I', getting the following error when I invoke the function:
Traceback (most recent call last): File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 346, in run_http_function result =
_function_handler.invoke_user_function(flask.request) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 217, in invoke_user_function return
call_user_function(request_or_event) File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 210, in call_user_function return
self._user_function(request_or_event) File "/user_code/main.py", line
74, in execute newIntro= generateIntroImage(nameMappings['stdName'],
nameMappings['stdPicture'], nameMappings['logo'],
nameMappings['stdYear'], nameMappings['font']) File
"/user_code/main.py", line 12, in generateIntroImage
images.append(Image.open(logo)) File
"/env/local/lib/python3.7/site-packages/PIL/Image.py", line 2862, in
open "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file '/tmp/logo.jpg'
I have ran this function on my local machine and it works as expected but when I deploy it on GCP, it gives this error and crashes. Here's my function:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def generateIntroImage(stdName, stdPicture, logo, year, typeFace):
images = [Image.open(x) for x in [stdPicture, logo]]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
font= ImageFont.truetype(typeFace, 70)
draw= ImageDraw.Draw(new_im)
draw.text((0, 0), stdName+"'s " +year+" Year Book", (0,0,0),font= font)
fileName= "/tmp/test.jpg"
new_im.save(fileName)
return fileName
These images are .jpg and .png files. Any idea what could be wrong?
Happened to me on Google Colab as well, apparently updating PIL version fixed the problem for me.
PIL throws error because it cannot identify the image format. Most probably the reason is that the image is corrupted and hence cannot be read (or "identified") by pillow's Image.open(). For example if you try opening the image in an IPython prompt, it would fail as well.
In [2]: from PIL import Image
In [3]: Image.open("176678612.jpg")
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-3-3f91b2f4e49a> in <module>
----> 1 Image.open("176678612.jpg")
/opt/conda/envs/swin/lib/python3.7/site-packages/PIL/Image.py in open(fp, mode, formats)
3022 warnings.warn(message)
3023 raise UnidentifiedImageError(
-> 3024 "cannot identify image file %r" % (filename if filename else fp)
3025 )
3026
UnidentifiedImageError: cannot identify image file '176678612.jpg'
And the relevant piece of code handling this check is from PIL.Image.open()
"""
exception PIL.UnidentifiedImageError: If the image cannot be opened and
identified.
"""
raise UnidentifiedImageError(
"cannot identify image file %r" % (filename if filename else fp)
So, the fix is to delete the image, or replace it with an uncorrupted version.
you need to provide a downloadable link to the image. What worked for me was click on the download image and the copy that URL.

tifffile cannot decompress JPEG because JPEG not in TIFF.DECOMPRESSORS

import tifffile
f = 'some.tif'
img = tifffile.imread(f)
Gives error:
~/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py in imread(files, **kwargs)
443 if isinstance(files, basestring) or hasattr(files, 'seek'):
444 with TiffFile(files, **kwargs_file) as tif:
--> 445 return tif.asarray(**kwargs)
446 else:
447 with TiffSequence(files, **kwargs_seq) as imseq:
~/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py in asarray(self, key, series, out, validate, maxworkers)
1900 typecode, product(series.shape), out=out, native=True)
1901 elif len(pages) == 1:
-> 1902 result = pages[0].asarray(out=out, validate=validate)
1903 else:
1904 result = stack_pages(pages, out=out, maxworkers=maxworkers)
~/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py in asarray(self, out, squeeze, lock, reopen, maxsize, validate)
3376 if self.compression not in TIFF.DECOMPESSORS:
3377 raise ValueError(
-> 3378 'cannot decompress %s' % self.compression.name)
3379 if 'SampleFormat' in tags:
3380 tag = tags['SampleFormat']
ValueError: cannot decompress JPEG
Note: It seems as though I only get the error for larger tif images. Also, the tifffile version is 0.15.1.
UPDATE-
After using pip to install imagecodes>=2018.10.22, I'm now getting the following error:
img=tifffile.imread(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/somename/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py", line 581, in imread
return tif.asarray(**kwargs)
File "/home/somename/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py", line 2042, in asarray
maxworkers=maxworkers)
File "/home/somename/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py", line 3813, in asarray
strip = decompress(strip)
File "/home/somename/.conda/envs/cmap_py3/lib/python3.6/site-packages/tifffile/tifffile.py", line 3700, in decompress
out)
File "/home/somename/.conda/envs/cmap_py3/lib/python3.6/site-packages/imagecodecs/imagecodecs.py", line 678, in jpeg_decode
'JPEG tables, colorspace, and outcolorspace otions not supported')
NotImplementedError: JPEG tables, colorspace, and outcolorspace otions not supported
On the linux machine on which tifffile can't open the large tif in ~/.conda/envs/cmap_py3/lib/python3.6/site-packages/imagecodecs I see
__init__.py
licencses
__pycache__
imagecodecs.py
On the windows machine on which tifffile can open the large tif in ls C:\\Anaconda2\\envs\\tensorflow35\\lib\\site-packages\\imagecodecs\\ I see
__init__.py
licenses
__pycache__
imagecodecs.py
_imagecodecs.cp35-win_amd64.pyd
_jpeg12.cp35-win_amd64.pyd
I think I had the same struggles as you, #user3731622
Try this code out, as recommended by #cgohlke:
!pip install tifffile
!pip install imagecodecs
import numpy
import tifffile as tiff
img = tiff.imread('/content/gdrive/My Drive/My Driver/imageToDriveExample.tif')
matrix = img[:,:,:]
print(matrix)

Specify where to save image taken with webcame Python

So I have a Python application that accesses the built-in webcam on a laptop and takes a picture. But I'm having difficulty specifying the storage location for the picture (in this case on the desktop). The code I have so far is:
import cv2
import time
import getpass
import os
getUser = getpass.getuser()
save = 'C:/Users/' + getUser + "/Desktop"
camera_port = 0
camera = cv2.VideoCapture(camera_port)
time.sleep(0.1)
return_value, image = camera.read()
os.path.join(cv2.imwrite(save, "user.png", image))
del camera
But when I run it I get the following error:
Traceback (most recent call last):
File "C:/Users/RedCode/PycharmProjects/MyApps/WebcamPic.py", line 13, in <module>
os.path.join(cv2.imwrite(save, "user.png", image))
TypeError: img is not a numpy array, neither a scalar
How can I specify where to store the image when it is taken?
This line here is where you have a problem.
os.path.join(cv2.imwrite(save, "user.png", image))
You want to do this
cv2.imwrite(os.path.join(save, "user.png"), image)
imwrite expects two arguments the file name and the image to be saved.
The call to os.path.join is building your saved file path.

Resources