If I run this:
import qrcode
img = qrcode.make('Some data here')
I don't know where it saves the actual image. I've tried CD'ing to a path and run the Python code, I have had the script in a directory. But when running the code above it doesn't create a QR image file in the directory. Where is it saved?!
I've tried running qr "Some data here" > test.png from the command-line which works perfectly. But not the module itself for some reason.
The make function doesn't output an image. For that you have to do something like this after running that function:
img = qr.make_image(fill_color="black", back_color="white")
Read the docs.
Related
I'm a beginner in python and I'm trying to send someone my small python program together with a picture that'll display when the code is run.
I tried to first convert the image to a binary file thinking that I'd be able to paste it in the source code but I'm not sure if that's even possible as I failed to successfully do it.
You can base64-encode your JPEG/PNG image which will make it into a regular (non-binary string) like this:
base64 -w0 IMAGE.JPG
Then you want to get the result into a Python variable, so repeat the command but copy the output to your clipboard:
base64 -w0 IMAGE.JPG | xclip -selection clipboard # Linux
base64 -w0 IMAGE.JPG | pbcopy # macOS
Now start Python and make a variable called img and paste the clipboard into it:
img = 'PASTE'
It will look like this:
img = '/9j/4AAQSk...' # if your image was JPEG
img = 'iVBORw0KGg...' # if your image was PNG
Now do some imports:
from PIL import Image
import base64
import io
# Make PIL Image from base64 string
pilImage = Image.open(io.BytesIO(base64.b64decode(img)))
Now you can do what you like with your image:
# Print its description and size
print(pilImage)
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x100>
# Save it to local disk
pilImage.save('result.jpg')
You can save a picture in byte format inside a variable in your program. You can then convert the bytes back into a file-like object using the BytesIO function of the io module and plot that object using the Image module from the Pillow library.
import io
import PIL.Image
with open("filename.png", "rb") as file:
img_binary = file.read()
img = PIL.Image.open(io.BytesIO(img_binary))
img.show()
To save the binary data inside your program without having to read from the source file you need to encode it with something like base64, use print() and then simply copy the output into a new variable and remove the file reading operation from your code.
That would look like this:
img_encoded = base64.encodebytes(img_binary)
print(img_binary)
img_encoded = " " # paste the output from the console into the variable
the output will be very long, especially if you are using a big image. I only used a very small png for testing.
This is how the program should look like at the end:
import io
import base64
import PIL.Image
# with open("filename.png", "rb") as file:
# img_binary = file.read()
# img_encoded = base64.encodebytes(img_binary)
img_encoded = b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABX[...]'
img = PIL.Image.open(io.BytesIO(base64.decodebytes(img_encoded)))
img.show()
You could perhaps have your Python program download the image from a site where you upload files such as Google Drive, Mega, or Imgur. That way, you can always access and view the image easily without the need of running the program or for example converting the binary back into the image in the method you mentioned.
Otherwise, you could always store the image as bytes in a variable and have your program read this variable. I'm assuming that you really wish to do it this way as it would be easier to distribute as there is only one file that needs to be downloaded and run.
Or you could take a look at pyinstaller which is made for python programs to be easily distributed across machines without the need to install Python by packaging it as an executable (.exe) file! That way you can include the image file together by embedding it into the program. There are plenty of tutorials for pyinstaller you could google up. Note: Include the '--onefile' in your parameters when running pyinstaller as this will package the executable into a single file that the person you're sending it to can easily open whoever it may be-- granted the executable file can run on the user's operating system. :)
I need to convert .ps files to .png files as part of an image recognition program I am making. I know I can use Ghostscript or other programs, but could someone give a specific example of how to write something like this:
def ps_to_png(ps_file):
file = ghostscript.read(ps_file)
png_file = ghostscript.save(file, "png")
return png_file
(This code is pseudo code- I want to know how to write something that actually does what this code looks like it will do.)
Thanks in advance! Stack is a great community and I appreciate it.
EDIT (Attempted solutions): When running this line:
os.system("ghostscript file.ps file.png")
I get the following Error:
'ghostscript' is not recognized as an internal or external command, operable program or batch file.
When attempting to use Pillow:
from PIL import Image
def convert_to_png(ps_file):
img = Image.open(ps_file)
img.save("img.png")
I get the following error:
OSError: Unable to locate Ghostscript on paths
You can use Pillow.
from PIL import Image
psimage=Image.open('myImage.ps')
psimage.save('myImage.png')
If you want to wrap it to a function:
from PIL import Image
def convert_to_png(path):
img = Image.open(path)
img.save("img.png")
path='/path_to_your_file'
convert_to_png(path)
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.
I have python script to split the capture.png(image) file into parts. Python script works fine when i run it individually and images are created correctly after splitting.
Am calling this python script from UFT code to do splitting job, but when it is called from UFT script runs and does nothing.
Please help me to solve this issue.
Below is the python code to split the image. I have developed a lib file (ImageExtractorTrial) to do my job. This will split my image and copy the splitted images in the same folder.
import ImageExtractorTrial
import cv2
from ImageExtractorTrial import pre_requisites_extractor
PreRequisites = pre_requisites_extractor().auto_extraction("Capture.png")
for req in PreRequisites:
cv2.imshow(req[1], cv2.imread(req[0]))
print("Image: %s"%req[0])
print("Status: %s"%req[1])
cv2.waitKey(0)
Below is the UFT code am using to call python script.
Set pyShell = CreateObject("Wscript.Shell")
pySplitimage = "python ""C:\Users\a291068\Desktop\Python\Python\codes\Splitimages.py"""
Set pyOperation = pyShell.Exec(pySplitimage)
Set pyResult = pyOperation.StdOut
wait(1)
pyReturn = pyResult.ReadAll
My python code works perfectly when run individually but does nothing when triggered from UFT.Please help me.
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.