Method works in one program but not the other - python

I'm programming a solution to a problem, and I've run into an issue with the PIL image method.
choice = input("Would you like to save the maze as a file, Y/N?").upper()
if choice == "Y":
canvas.update()
canvas.postscript(file="maze.eps", colormode='color')
img = Image.open("maze.eps")
However I get the following error message:
Traceback (most recent call last):
File "C:\Users\Matthew\Desktop\NEA\Technical Solution\mazeVisualiser.py", line 66, in <module>
img = Image.open("maze.eps")
AttributeError: type object 'Image' has no attribute 'open'
But while learning the PIL module I know this is valid like so:
from PIL import Image
img = Image.open('brick-house.png')
Any help would be greatly appreciated as this has got me completely stuck.

Try This:
import PIL.Image
fp = open("brick-house.png", "rb")
img = PIL.Image.open(fp)
img.show()

Related

I am trying to save this image in a folder but it is showing this error. What am I doing wrong here?

This is my code
from PIL import Image
from PIL import ImageDraw
# Open an Image
FRAME_SIZE = (720,1280)
img = Image.new('RGB', FRAME_SIZE, color = 'black')
# Call draw Method to add 2D graphics in an image
I1 = ImageDraw.Draw(img)
# Add Text to an image
I1.text((100, 100), "nice Car", fill=(255, 32, 0))
# Display edited image
img.show()
# Save the edited image
img.save("./new_folder/car2.png")
And this is error.
Traceback (most recent call last):
File "D:\Python Projects\devops-directive-hello-world\trial.py", line 19, in <module>
img.save("./new_folder/car2.png")
File "C:\Users\Pushpendra\Desktop\Drone\devops-directive-hello-world\lib\site-packages\PIL\Image.py", line 2317, in save
fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: './new_folder/car2.png'
Process finished with exit code 1
Just change the destination folder.
img.save("car2.png")
this will do the trick. At least you must choose an existing directory
The most possible reason for this error to occur is your Python directory is in C: so your relative path is referencing your Python directory only.
Work around in this case can be to use absolute path, like so : 'D/Python Projects/newfolder/'
Hopefully it solves your problem

"cannot identify image file"-error when trying to load a tiff in python

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)

Python - Read image from a URL then use for face_recognition?

I am trying to feed an image from URL to a face_recognition library that I'm using, but it does not seem to be working.
I have tried the suggestion here: https://github.com/ageitgey/face_recognition/issues/442 but it did not work for me. I'm thinking that my problem is with the method that I'm using for fetching the image, and not the face_recognition library, that's why I decided to post the question here.
Bellow is my code:
from PIL import Image
import face_recognition
import urllib.request
url = "https://carlofontanos.com/wp-content/themes/carlo-fontanos/img/carlofontanos.jpg"
img = Image.open(urllib.request.urlopen(url))
image = face_recognition.load_image_file(img)
# Find all the faces in the image using the default HOG-based model.
face_locations = face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
# Print the location of each face in this image
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# You can access the actual face itself like this:
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.show()
I'm getting the following response when running the above code:
Traceback (most recent call last):
File "test.py", line 10, in <module>
image = face_recognition.load_image_file(img)
File "C:\Users\Carl\AppData\Local\Programs\Python\Python37-32\lib\site-packages\face_recognition\api.py", line 83, in load_image_file
im = PIL.Image.open(file)
File "C:\Users\Carl\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\Image.py", line 2643, in open
prefix = fp.read(16)
AttributeError: 'JpegImageFile' object has no attribute 'read'
I think the problem is with the line AttributeError: 'JpegImageFile' object has no attribute 'read'
You don't need Image to load it
response = urllib.request.urlopen(url)
image = face_recognition.load_image_file(response)
urlopen() gives object which has methods read(), seek() so it is treated as file-like object. And load_image_file() needs filename or file-like object
urllib.request.urlopen(url) returns a http response and not an image file. i think you are supposed to download the image and give the path of the files as input to load_image_file().

TypeError: NoneType, when trying to loop crop images

from os import listdir
import cv2
files=listdir('/home/raymond/Desktop/Test/Test') #Importing the dir for cropping
for file in files:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
crop_img = img[0:1600, 0:1600]
cv2.imwrite('/home/raymond/Desktop/Test/cropped'+file,crop_img) # write new data to img
Im trying to loop crop images, while getting an error of
Traceback (most recent call last):
File "Files.py", line 8, in <module>
crop_img = img[0:1600, 0:1600]
TypeError: 'NoneType' object is not subscriptable
(fixi) ➜ exercises
You are probably missing a slash at the end of the path here:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
Should be:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file) # reading a single image from the dir
or even better:
import os
img = cv2.imread(os.path.join('/home/raymond/Desktop/Test/Test/',file)) # reading a single image from the dir
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file)
Hello Dan Raymond,
This cannot work because Python does not add a slash (/) before listed filenames.
Which means that if you have a filename "hello", then what is appended to '/home/raymond/Desktop/Test/Test' is "hello" which results in '/home/raymond/Desktop/Test/Testhello' which does not exist.
Replace your line with this:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file)

Adding noise to an image in increments

Hi I am trying to add noise to a QR image that I create, this is my code so far:
import numpy
import scipy
import scipy.misc
import sys
sys.path.append('M:/PythonMods')
import qrcode
if __name__ == "__main__":
myqr = qrcode.make("randomtexxxxxxxxxt")
#myqr.show()
myqr.save("M:/COMPUTINGSEMESTER2/myqr4.png")
filename = 'myqr4.png'
imagea = (scipy.misc.imread(filename)).astype(float)
poissonNoise = numpy.random.poisson(50,imagea.shape).astype(float)
noisyImage = imagea + poissonNoise
Please could someone advise me how I get it to show the noisy image? and how to save the image so I can test it?
Any help really appreciated.
edit
I tried adding this code to the program to get it to show the image:
from PIL import Image
myimage = Image.open(noisyImage)
myimage.load()
But then got this error:
Traceback (most recent call last):
File "M:\COMPUTINGSEMESTER2\untitled4.py", line 28, in <module>
myimage = Image.open(noisyImage)
File "Q:\PythonXY273_MaPS-T.v01\Python27\lib\site-packages\PIL\Image.py", line 1958, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'
Image.open needs an image file as parameter, use Image.fromarray:
im = Image.fromarray(noisyImage)
im.save("myFile.jpeg")
you may also use matplotlib module to show the image directly:
import matplotlib.pyplot as plt
plt.imshow(noisyImage) #Needs to be in row,col order
scipy.misc.imsave('NoisyImage.jpg', noisyImage)

Categories