This question already has answers here:
Can I access ImageMagick API with Python?
(3 answers)
Closed 9 years ago.
I want to define a function that "call" imagemagick to convert an image.
def convert(filein,fileout):
#imagemagick>convert filein fileout
How can I call and use imagemagick with Python?
I'm running on a linux system, imagemagick is installed, and I'm not using PIL.module because it doesn't handle PPM[p3].
Disclaimer: I am the author of Wand.
You can easily do that using Wand, a simple binding of ImageMagick for Python. For example, the following code converts a PNG image to a JPEG image:
from wand.image import Image
with Image(filename='in.png') as img:
img.format = 'jpeg'
img.save(filename='out.jpg')
See this tutorial as well.
Either use one of the shell interfaces of Python (os.system, subprocess.Popen) to call the imagemagick binary, or try out PythonMagick.
I would suggest u use subprocess it is safer
import subprocess
params = ['convert', 'src_file', 'result_file']
subprocess.check_call(params)
I have not used image magic but you could use os.system to call a shell command:
import os
os.system('imagemagick-converting-command filein fileout')
I suggest you go with PythonMagic as Creshal said. It is provided by ImageMagic and thus must be one of the best port available for python.
Related
Need to convert 50 images, and doing it manually would be too long.
Сan't find a library with such function.
I tried Pillow, but it can't save in dds.
I found that I can use the command line app in python, so image magic covers all my needs.
You could use Wand library:
from wand import image
with image.Image(filename='your.png') as img:
img.compression = 'dxt5'
img.save(filename='your.dds')
It appears that this library might be useful for you, check it out: https://github.com/ducakar/img2dds
In regards to #Yuri Leonov post above. In Python3 I had to specify reading mode in open() command to get it to work.
from wand import image
with image.Image(filename=r'yourimage.png') as img:
img.compression = 'dxt5'
img.save(filename='yourimage.dds')
I'm trying to open Image file from PyFileSystem MemoryFS using PIL, I tried to do that like this example and i got the error below:
from PIL import Image
from fs.memoryfs import MemoryFS
fs=MemoryFS()
fs.makedir("test")
out=fs.open("test/file.jpg",'wb')
out.write(someimagefile.read())
out.close()
in=fs.open("test/file.jpg",'rb')
im=Image.open(in) #error: cannot identify image file <IO wrapper for <MemoryFile in <MemoryFS> test/file.jpg>>
however if I don't use a directory (ex. out=fs.open("file.jpg",'wb')) It does work as expected.
What am I doing wrong?
Thanks for your help.
I already get an error using the following line:
from fs.memoryfs import MemoryFS
Probably I don't have that library installed. Do you need this library? You can just open the image without opening it with MemoryFS:
im = Image.open("test/file.jpg")
Side note: I wouldn't use in as variable name, since it is also a Python keyword.
I am trying to create a gif using python either through the GraphicsMagick module or using os.system commands with the ImageMagick.exe. The most relevant question I have found here was this question about 6 years ago.
Similar Question 6 years old
URL for imagemagick download
file:///C:/Program%20Files/ImageMagick-6.9.1-Q16/www/binary-releases.html#windows
GraphicsMagick Download
Below is my code (not working). I am currently trying the ImageMagick route as the above question stated that this was more pythonic. Any help would be appreciated.
from pgmagick import Image, ImageList, Geometry, Color
import os, sys
import glob
#dataDir = sys.argv[1]
#outDir = sys.argv[2]
dataDir = 'C:\\Users\\name\\Desktop\\a'
os.chdir(dataDir)
fileList = glob.glob(dataDir + '\*.jpg')
fileList.sort()
os.system('convert fileList -delay 20 -loop 0 *jpg animated.gif')
I get an invalid syntax error on the last line of my code.
For anyone that sees this in the future when trying to make a gif with imagemagick on a windows machine, this is the solution that I figured out. I don't know if this is the most efficient way in terms of memory, but it works.
import os, sys
dataDir = 'fullpath of directory with images'
os.chdir(dataDir)
os.system('SETLOCAL EnableDelayedExpansion')
#This is the path of the imagemagick installation convert command.
#The invalid parameter I was getting was because the computer was trying to
#use a different convert command. This code sets convert as a different
#variable and then calls that new variable as the convert command.
os.system('SET IMCONV="C:\Program Files\ImageMagick-6.9.1-Q16\Convert"')
os.system('%IMCONV% *.jpg animated.gif')
Some changes I made to simplify the solution. Instead of making a file list as I did in my question, I just stuck all the images in a directory, and then called the command to convert these images to a gif. This is the simplest solution that I have come across.
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 )
I need to use ImageMagick as PIL does not have the amount of image functionality available that I am looking for. However, I am wanting to use Python.
The python bindings (PythonMagick) have not been updated since 2009. The only thing I have been able to find is os.system calls to use the command line interface but this seems clunky.
Is there any way to access the API directly using ctypes and conversions of some sort?
As a last resort is there any other library out there that has the extensive amount of image editing tools like ImageMagick that I have looked over?
I would recommend using Wand (explanations follows).
I was looking for proper binding to ImageMagick library, that would:
work error/problem free
be regularly maintained and up to date
allow nice objective Python
But indeed python API (binding) has too many different (mostly discontinued) versions. After reading a nice historical overview by Benjamin Schweizer it has all become clear:
GraphicsMagick
PythonMagick - first implementation
PythonMagickWand/Achim Domma - first Wand - a CDLL implementation
PythonMagickWand/Ian Stevens
MagickFoo - included in python-magickwand
Wand/Hong Minhee - not the latest project
[UPD 2023] Eric McConville https://github.com/emcconville/wand
Now Wand is just a (reduced) C API to the ImageMagick ".. API is the recommended interface between the C programming language and the ImageMagick image processing libraries. Unlike the MagickCore C API, MagickWand uses only a few opaque types. Accessors are available to set or get important wand properties." (See project homepage)
So it is already a simplified interface that is easer to maintain.
[UPD 2023] PS as any API software py-wand inherits any transient errors from the parent
This has worked for me for the following command to create an image from text for the letter "P":
import subprocess
cmd = '/usr/local/bin/convert -size 30x40 xc:white -fill white -fill black -font Arial -pointsize 40 -gravity South -draw "text 0,0 \'P\'" /Users/fred/desktop/draw_text2.gif'
subprocess.call(cmd, shell=True)
I found no good Python binding for ImageMagick, so in order to use ImageMagick in Python program I had to use subprocess module to redirect input/output.
For example, let's assume we need to convert PDF file into TIF:
path = "/path/to/some.pdf"
cmd = ["convert", "-monochrome", "-compress", "lzw", path, "tif:-"]
fconvert = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = fconvert.communicate()
assert fconvert.returncode == 0, stderr
# now stdout is TIF image. let's load it with OpenCV
filebytes = numpy.asarray(bytearray(stdout), dtype=numpy.uint8)
image = cv2.imdecode(filebytes, cv2.IMREAD_GRAYSCALE)
Here I used tif:- to tell ImageMagick's command-line utility that I want to get TIF image as stdout stream. In the similar way you may tell it to use stdin stream as input by specifying - as input filename.