imagemagick with grayscale not working - imagemagick

I am trying to change a file named "anvil_base.png" to grayscale so I am using imagemagick. What I am entering is convert anvil_base.png -colorspace Gray -gamma 2.2 anvil_base.png
but it is just returning this
Invalid Parameter - -colorspace
What am I doing wrong?

I suspect you are on Windows and you have not put the directory where ImageMagick is installed ahead of other directories in your PATH. You have three choices:
Option 1
As Glenn kindly points out, if you are using ImageMagick version 7 or newer, you can use the new name for convert which is magick, like this:
magick image.png -colorspace gray ...
Option 2
Use the full path to ImageMagick every time, something like this:
C:\ImageMagick-6.9.3\convert ...
Option 3
Change your PATH. So you would need to do:
Start->Programs->Control Panel->System->Advanced
and then choose Environment Variables and change PATH so that it looks like:
PATH=C:\ImageMagick-6.9.3;C:\Windows;C:\Windows\System32
The main thing is that ImageMagick directory is at the start of the PATH. Then Windows will find the convert which is part of ImageMagick before it finds the built-in Windows convert program which converts FAT filesystems to NTFS. If you choose Option 3 above, you need to either log out and back in again, or start a new Command Prompt for the new PATH to become active.

Related

How to use mogrify (ImageMagick) to convert from NEF to *.jpg and retain EXIF data?

I'm converting about 9000 photos from .NEF to .jpg.
I'd like to retain all EXIF data, most importantly Date and time created, Latidude and Longitude.
I'd like the JPGs to be at the highest possible quality.
I've just gotten started using ImageMagick from the command line. I also have Exiftool installed. I'm using the mogrify command because it handles batches nicely.
When I run
mogrify -format jpg *.NEF
All of my .NEF files are successfully converted to JPGs, but all EXIF data are lost.
I've searched around quite a bit to try and find a solution to this and it seems like I may have to install ufraw, but if possible I'd like a solution that uses software I already have - ImageMagick and Exiftool.
Thanks in advance for any advice you have about how to do this.
Update:
The images I converted using mogrify are slightly smaller (~ 1-2 MB) than those output by my colleague using picasa to convert NEF to JPG. But when I specify -quality 100 in ImageMagick the image sizes gain about 45 MB! Why?
The code exiftool -tagsfromfile %d%f.NEF -ext jpg -overwrite_original . adds the exif information to the JPGs.
Think twice before doing this - you really are discarding a lot of information - and if you don't want it, why not shoot JPEG instead of RAW in the first place?
FWIW, you can use ImageMagick to get the JPEG:
convert somefile.NEF somefile.jpg
Then you can copy the tags across from the original to the file newly created by ImageMagick:
exiftool -tagsfromfile somefile.NEF -all:all somefile.jpg
If you have thousands of images, and are on macOS or a decent Linux/Unix-based OS, I would recommend GNU Parallel like this and it will keep busy all those lovely cores that you paid Intel so dearly for:
parallel --dry-run 'convert {} {.}.jpg; exiftool -tagsfromfile {} -all:all {.}.jpg' ::: *nef
Sample Output
convert a.nef a.jpg; exiftool -tagsfromfile a.nef -all:all a.jpg
convert b.nef b.jpg; exiftool -tagsfromfile b.nef -all:all b.jpg
and if that looks good remove the --dry-run so it actually runs the command.
If you are on Windows, you will have to do some ad-hoc jiggery-pokery to get it done in any reasonable time frame. You can use the mogrify command and get all the conversions done to JPEG and then do all the exiftool re-embedding of the EXIF data later. If your files are named with some sort of system with incrementing numbers, you can start two or three copies of mogrify in parallel - say one doing files whose names end in [0-4] and another one doing files whose names end in [5-9]. I don't speak Windows, but that would probably look like these two commands each running in its own Command Prompt:
mogrify -format jpg *0.NEF *1.NEF *2.NEF *3.NEF *4.NEF
mogrify -format jpg *5.NEF *6.NEF *7.NEF *8.NEF *9.NEF
Then you would do the exiftool stuff when they had all finished but you would have to use a FOR loop like this:
FOR %%G IN (*.NEF) DO (
exiftool -tagsfromfile %%G -all:all %%~dpnG.jpg
)
The %%~dpnG part is a guess based on this answer.

Batch converting .eps to .jpg in imagemagick and making .mkv

I am trying to convert multiple .eps files into .jpg ones. By looking at answers here in SO, I was able to do it for single separate files.
The problem is that, when I'm trying to do it for all the files, they don't show any .jpg file.
I am currently using Imagemagick with the command
convert -density 300 outputs-000.eps -flatten outputs-000.jpg
I believe the problem is because my files are written as
outputs-000.eps
outputs-001.eps
outputs-002.eps
outputs-003.eps
...
outputs-145.eps
...
and so on. I tried putting %d (as in outputs-%d.eps and outputs-%d.jpg), but with no success.
Apart from that, I intent to get all those files and "convert" them into an .mkv or .gif or similar type (they are images of the time configuration of a particle collision system, so each image is a frame, so the goal is to make it into a 10sec movie). If there is a way to do that directly from the .eps, even better. Any help is welcome, since I've been trying to do this for several hours now. Thank you.
You should be able to make an animated GIF in one go like this:
convert -density 300 outputs-*eps -delay 200 animated.gif
Failing that, you should be able to convert all your eps files to, say PNG with:
mogrify -density 300 -format png outputs-*eps
Be careful with mogrify - it overwrites your input files unless you specify -path for an output directory, or you change format - like I just did to PNG.
For anyone who lands here trying to figure out how to work around ImageMagic's convert: not authorized without reverting the change that was made to the system-wide security policy to close a vulnerability, here's how you'd use Ghostscript to do a batch EPS-to-JPEG conversion directly without bringing ImageMagick into the mix:
gs -dSAFER -dEPSCrop -r300 -sDEVICE=jpeg -o outputs-%03d.jpg outputs-*.eps
-dSAFER puts Ghostscript in a sandboxed mode where Postscript code can only interact with the files you specified on the command line. (Yes, the parts of EPS, PS, and PDF files that define the page contents are in a turing-complete programming language.)
-dEPSCrop asks for the rendered output to be cropped to the bounding box of the drawing rather than padded out to whatever size page Ghostscript expects you to be printing to. (See the manual for details.)
The -r300 requests 300 DPI (-r600 for 600 DPI, etc.)
The -sDEVICE specifies the output format (See the Devices section of the manual for other choices.)
-o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=
This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.
Once you've got your JPEGs, you can follow the instructions in this answer over on the Video Production Stack Exchange to combine them into an MKV file.
The TL;DR is this command here:
ffmpeg -framerate 30 -i outputs-%03d.jpg -codec copy output.mkv
Check out the other answers if you want something that performs inter-frame compression rather than aiming to avoid transcoding the JPEGs again.
(If you want the best compromise, have Ghostscript output PNGs and then let ffmpeg handle switching to lossy compression.)

How to convert .xcf files to .png files in batch?

I'm using Windows. I have a folder with .xcf files, each 100x100px. I would like to run a process that will convert them to .png files making them 40x40px. How can I do that?
You might succeed using ImageMagick which also supports XCF for reading. They also provide Windows binaries. The tool also has various transformation (scaling) options, so you can convert and scale each image with one call:
convert source.xcf -resize 40x40 target.png
I'm not fluent with Windows batch programming and don't have access to Windows PC right now, I think a simple loop would look something like this:
for %%f in (*.xcf) do (
convert %%f -resize 40x40 %%~nf.png
)

ImageMagick to verify image integrity

I'm using ImageMagick (with Wand in Python) to convert images and to get thumbnails from them. However, I noticed that I need to verify whether a file is an image or not ahead of time. Should I do this with Identify?
So I would assume checking the integrity of a file needs the whole file to be read into memory. Is it better to try and convert the file and if there was an error, then we know the file wasn't good.
seems like you answered your own question
$ ls -l *.png
-rw-r--r-- 1 jsp jsp 526254 Jul 20 12:10 image.png
-rw-r--r-- 1 jsp jsp 10000 Jul 20 12:12 image_with_error.png
$ identify image.png &> /dev/null; echo $?
0
$ identify image_with_error.png &> /dev/null; echo $?
0
$ convert image.png /dev/null &> /dev/null ; echo $?
0
$ convert image_with_error.png /dev/null &> /dev/null ; echo $?
1
if you specify the regard-warnings flag with the imagemagick identify tool
magick identify -regard-warnings myimage.jpg
it will throw an error if there are any warnings about the file. This is good for checking images, and seems to be a lot faster than using verbose.
I the case you use Python you can consider also the Pillow module.
In my experiments, I have used both the Pyhton Pillow module (PIL) and the Imagemagick wrapper Wand (for psd, xcf formats) in order to detect broken images, the original answer with code snippets is here.
Update:
I also implemented this solution in my Python script here on GitHub.
I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it.
End Update
I quote the full answer for completeness:
You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.
In the case you aim at detecting also broken images, #Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).
Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:
try:
im = Image.load(filename)
im.verify() #I perform also verify, don't know if he sees other types o defects
im.close() #reload is necessary in my case
im = Image.load(filename)
im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
im.close()
except:
#manage excetions here
In case of image defects this code will raise an exception.
Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations).
With this code you are going to verify a set of images at about 10 MBytes/sec (using single thread of a modern 2.5Ghz x86_64 CPU).
For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:
im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()
But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.
I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.
I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:
statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
#manage here the 'faulty image' case
Here's another solution using identify, but without convert:
identify -verbose *.png 2>&1 | grep "corrupt image"
identify: corrupt image 'image_with_error.png' # error/png.c/ReadPNGImage/4051.
i use identify:
$ identify image.tif
00000005.tif TIFF 4741x6981 4741x6981+0+0 8-bit DirectClass 4.471MB 0.000u 0:00.010
$ echo $?

Paperclip::NotIdentifiedByImageMagickError in Spree::Admin::ImagesController#create

I am attempting to setup Spree for the first time. Everything was going well until I hit the image upload. I have installed Imageamgick using homebrew on Mac OSX Mountain Lion. Uploading any image gives me the following error.
Paperclip::NotIdentifiedByImageMagickError in Spree::Admin::ImagesController#create
Command :: identify -format %wx%h :file
[paperclip] An error was received while processing: #<Paperclip::NotIdentifiedByImageMagickError: /var/folders/fq/9g_6hmg513g6137rb6sbghw00000gn/T/stream20121005-26943-16883d4.png is not recognized by the 'identify' command.>
Paperclip::NotIdentifiedByImageMagickError (/var/folders/fq/9g_6hmg513g6137rb6sbghw00000gn/T/stream20121005-26943-16883d4.png is not recognized by the 'identify' command.):
paperclip (2.7.1) lib/paperclip/geometry.rb:29:in `from_file'
spree_core (1.2.0) app/models/spree/image.rb:35:in `find_dimensions'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `_run__1794851703999987262__post_process__1580526166879208018__callbacks'
When I run identify from the command line I get the following output
Image Settings:
-alpha option on, activate, off, deactivate, set, opaque, copy
transparent, extract, background, or shape
-antialias remove pixel-aliasing
-authenticate password
decipher image with this password
-channel type apply option to select image channels
-colorspace type alternate image colorspace
-crop geometry cut out a rectangular region of the image
-define format:option
define one or more image format options
-density geometry horizontal and vertical density of the image
-depth value image depth
-extract geometry extract area from image
-features distance display image features (e.g. contrast, correlation)
-format "string" output formatted image characteristics
-fuzz distance colors within this distance are considered equal
-gamma value of gamma correction
-interlace type type of image interlacing scheme
-interpolate method pixel color interpolation method
-limit type value pixel cache resource limit
-monitor monitor progress
-ping efficiently determine image attributes
-quiet suppress all warning messages
-regard-warnings pay attention to warning messages
-respect-parentheses settings remain in effect until parenthesis boundary
-sampling-factor geometry
horizontal and vertical sampling factor
-seed value seed a new sequence of pseudo-random numbers
-set attribute value set an image attribute
-size geometry width and height of image
-strip strip image of all profiles and comments
-unique display the number of unique colors in the image
-units type the units of image resolution
-verbose print detailed information about the image
-virtual-pixel method
virtual pixel access method
Image Operators:
-negate replace every pixel with its complementary color
Miscellaneous Options:
-debug events display copious debugging information
-help print program options
-list type print a list of supported option arguments
-log format format of debugging information
-version print version information
By default, the image format of `file' is determined by its magic
number. To specify a particular image format, precede the filename
with an image format name and a colon (i.e. ps:image) or specify the
image type as the filename suffix (i.e. image.ps). Specify 'file' as
'-' for standard input or output.
Any help would be greatly appreciated.
Thanks,
Cory
My error was - “Paperclip::NotIdentifiedByImageMagickError in Spree::Admin::ImagesController”
I fixed this error some days ago.
Before that I tried:
Update XCode (with Command-Line Tools)
Update Imagemagick (i tried it from source and as binary module)
Update MacPort
Used Brew (refreshing with all dependencies for Imagemagic,
used “brew doctor”), not MacPort
Reinstall all gems that use Imagemagick
Bundle update
etc
And sure I had my “Paperclip::Attachment.default_options[:command_path]” option in production.rb file pointing to Imagemagick bin folder.
Several times i did it from a to z, again and again.
But nothing could help me.
By the way, in all cases i had worked fine “convert”, “identify” and “display” with test images of any kind, but not in my rails app (spree app).
I dived dipper and tried to do research inside rails console with
Paperclip.run("identify", "-format %m :file", :file => "/path/to/image”)
as paperclip do. And only new format (cocaine 0.4) of this command:
Paperclip.run("identify", "-format %m /path/to/image")
worked fine!!!
As a result, i found that cocaine 0.4 is the source of my problem. I tried downgrade to cocaine 0.3.2 in my Gemfile and my Spree app start working!!!
All i need to do is use cocaine 0.3.2 instead of 0.4!!!
Check if png format is in the list of compiled formats of identify:
identify -list format
If it's not, you might have to recompile it with these options:
./configure --prefix=/usr/local --with-bzlib=yes --with-fontconfig=yes --with-freetype=yes --with-gslib=yes --with-gvc=yes --with-jpeg=yes --with-jp2=yes --with-png=yes --with-tiff=yes
Also I met the problem when image file doesn't exists in public folder.
I've just copied a random file with the same name and everything started work.
parepclip 2.7.5 cocain 0.3.2

Resources