I am trying to read scanned images from a pdf using wand and display it using PIL. But I get some error. First page of the pdf file works perfectly but the second page shows this error.
Code
from wand.image import Image
from wand.display import display
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import numpy as np
import cStringIO
tool = pyocr.get_available_tools()[0]
lang = tool.get_available_languages()[1]
req_image = []
final_text = []
image_pdf = Image(filename="DEEP_PLAST_20.700.pdf", resolution=200)
image_jpeg = image_pdf.convert('jpeg')
img_page = Image(image=image_jpeg.sequence[1])
img_buffer = np.asarray(bytearray(img_page.make_blob()), dtype=np.uint8)
print(img_buffer)
# im = PI.fromarray(img_buffer)
im = PI.open(cStringIO.StringIO(img_buffer))
I get this error.
Traceback (most recent call last):
File "ocr.py", line 43, in <module>
im = PI.open(cStringIO.StringIO(img_buffer))
File "/home/sahil/anaconda2/lib/python2.7/site-packages/PIL/Image.py", line 2452, in open
% (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringI object at 0x7fc4a8f168b0>
I don't why the code fails on the second page of the pdf whereas it works for the first one.
Any help would be appreciated!
Related
import mysql.connector
import base64
import io
from base64 import b64decode
from PIL import Image
import PIL.Image
with open('assets\zoha.jpeg', 'rb') as f:
photo = f.read()
encodestring = base64.b64encode(photo)
db=
mysql.connector.connect(user="root",password="",
host="localhost",database="pythonfacedetection")
mycursor=db.cursor()
sql = "INSERT INTO image(img) VALUES(%s)"
mycursor.execute(sql,(encodestring,))
db.commit()
sql1="select img from image where id=75"
mycursor.execute(sql1)
data = mycursor.fetchall()
image=data[0][0]
img = base64.b64decode(str(image))
img2=io.BytesIO(img )
img3= Image.open(img2)
img.show()
db.close()
I want to save my photo in database and display that photo from the database. The data has save on the database properly but can not display. I tried a lot but every time this error shows. Please advise me how can I solve this.
Traceback (most recent call last):
File "C:/Users/MDSHADMANZOHA/PycharmProjects/ImageFromDatabase/main.py", line 28, in
<module>
img3= Image.open(img2)
File "C:\Users\MDSHADMANZOHA\PycharmProjects\ImageFromDatabase\venv\lib\site-
packages\PIL\Image.py", line 3009, in open
"cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at
0x0000020247DCE308>
I am using PIL to make an application to open all images in a folder. I sought for tutorials for PIL. I tried to find tutorials with list of images, but I failed to do so. I found some, but I had to list the file location beforehand. It annoyed me. So, instead I want the user to choose a folder, and the application would load all the images for the user. But, while making the thumbnails for the list of images, I got an error which I'm not familiar with. This is the exact error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line
1892, in __call__
return self.func(*args)
File "f:\OG\Python\ImageViewer.py", line 47, in openFolder
GetFiles()
File "f:\OG\Python\ImageViewer.py", line 87, in GetFiles
with Image.open(i) as img:
prefix = fp.read(16)
raise AttributeError(name)
The minimal code to get this error is:
import glob
from PIL import Image, ImageTk
fileDir = "Your Folder"
imageList = []
image_list = []
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
im = Image.open(filename)
imageList.append(im)
for i in imageList:
with Image.open(i) as img: # This raises the error
imageList[i] = img.thumbnail((550, 450))
for i in image_list: # Would this work?
image_list[i] = ImageTk.PhotoImage(imageList[i])
I would like to know if the code that is commented with 'Would this work?' would work or not.
Just remove the reading part again which doesn't make sense
import glob
from PIL import Image, ImageTk
fileDir =r"your path"
imageList = []
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
im = Image.open(filename)
imageList.append(im)
imageList will look like this :
[<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x200 at 0x25334A87D90>]
here is the blockbuster solution
import glob
from PIL import Image, ImageTk
import PIL
from pathlib import Path
fileDir = r"your_path_here"
imageList = []
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
im = Image.open(filename)
imageList.append(im)
im.thumbnail((550, 450))
im.save(fileDir+'/'+Path(filename).name.split('.')[0]+'_thumbnail.png')
I solved it, I edited the code as follows:
import glob
from PIL import Image, ImageTk
fileDir = "Your Folder"
imageList = []
image_list = []
count = 0
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
imageList.append(filename)
for i in imageList:
with Image.open(i) as img:
i = img.thumbnail((550, 450))
for i in imageList: # This gives a Key Error Now
image_list.append(ImageTk.PhotoImage(imageList[count]))
count = count + 1
Basically, Introduced a new variable count with a value of 0, removed open from first for loop, used append method for the last for loop and added count 1 each time :)
I am trying to access to the temperature data stored in a tiff-file. I was provided with a python script that was supposed to be able to do this, but I keep getting the following error:
Traceback (most recent call last):
File "read_tiff.py", line 57, in <module>
im = Image.open(sourcePath)
File "/Users/myname/opt/anaconda3/lib/python3.8/site-packages/PIL/Image.py", line 2943, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file 'Testbild.tiff'
This is the relevant section of the code:
sourcePath = "Testbild.tiff"
im = []
try:
sourcePath = sys.argv[1]
except IndexError:
print('usage: python read_tiff.py filename')
sys.exit()
try:
im = Image.open(sourcePath)
except FileNotFoundError:
print('File not found: ' + sourcePath)
sys.exit()
imarray = np.array(im)
This is what I checked:
with another random tiff file it worked, so it is probably not the script but the file itself (/maybe I need to install some additional package??)
the tiff file can be opened without a problem in IrfanView and Photoscan
when prompting "file Testbild.tiff" I get "Testbild.tiff: TIFF image data, little-endian" so it definitely IS a tiff file
Is anyone able to help me out?
Cheers!
EDIT:
The import statement for Image is from PIL import Image
If necessary, these are all the import statements of the script:
import matplotlib.pyplot as plt
from PIL import Image
import sys
import numpy as np
import math
import cv2
Try using:
from skimage import io
im = io.imread(sourcePath)
This will open it directly as an array as well.
In my case, it worked to read .tif file to ndarray:
path2dir = r'C:\data\WORK\image4example'
name_img = 'Slice_25.tif'
path2img = os.path.join(path2dir, name_img)
im = cv2.imread(path2img , cv2.IMREAD_ANYDEPTH)
plt.imshow(im)
i want to encoding some of folders that contain face images.
this is the code that i've been tried.
import face_recognition
import cv2
import numpy as np
import os
import glob
video_capture = cv2.VideoCapture(0)
known_face_encodings = []
known_face_names = []
# Load image folder and learn how to recognize it.
os.chdir("./coba1")
for file in glob.glob("*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
known_face_names.append("jokowi")
print(images_encoding)
#Load image folder and learn how to recognize it.
os.chdir("./coba")
for file in glob.glob("*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
known_face_names.append("amber heard")
print(images_encoding)
when i run the code, the terminal shows this warning
Traceback (most recent call last):
File "face_rec.py", line 32, in <module>
os.chdir("./coba")
FileNotFoundError: [Errno 2] No such file or directory: './coba'
is there anything wrong with my code? i really need the solution, thanks in advance !
I am completely new to Python and I'm trying to figure out how to read an image from a URL.
Here is my current code:
from PIL import Image
import urllib.request, io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
s = url.read()
Image.open(s)
I get the following error:
C:\python>python image.py
Traceback (most recent call last):
File "image.py", line 8, in <module>
Image.open(s)
File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte
I have no idea what any of this means. What am I doing wrong?
Image.open() expects filename or file-like object - not file data.
You can write image locally - i.e. as "temp.jpg" - and then open it
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
with open('temp.jpg', 'wb') as f:
f.write(url.read())
img = Image.open('temp.jpg')
img.show()
Or you can create file-like object in memory using io module
from PIL import Image
import urllib.request
import io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
f = io.BytesIO(url.read())
img = Image.open(f)
img.show()
EDIT: 2022
Because urlopen() also gives file-like object so you can even skip io and use directly url (without .read()) in Image.open()
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
img = Image.open(url)
img.show()
Here's how to read an image from a URL using scikit-image
from skimage import io
io.imshow(io.imread("http://www.w3schools.com/css/trolltunga.jpg"))
io.show()
Note: io.imread() returns a numpy array
To begin with, you may download the image to your current working directory first
from urllib.request import urlretrieve
url = 'http://www.w3schools.com/css/trolltunga.jpg'
urlretrieve(url, 'pic.jpg')
And then open/read it locally:
from PIL import Image
img = Image.open('pic.jpg')
# For example, check image size and format
print(img.size)
print(img.format)
img.show()
As suggested in this stack overflow answer, you can do something like this:
import urllib, cStringIO
from PIL import Image
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
Then you can use your image freely.
For example, you can convert it to a numpy array:
img_npy = np.array(img)