Combining images from folder two by two in imagemagick - imagemagick

Combining images from folder two by two in imagemagick.
Hi there,
I have a folder with images such as this list:
image1.jpg
image2.jpg
image3.jpg
alphaplupp.jpg
kj56.jpg
rumiba54.jpg
How can I use imagemagick to merge all of them horizontally like so:
image1.jpg+image2.jpg
image3.jpg+alphaplupp.jpg
kj56.jpg+rumiba54.jpg
Vesa

I don't normally write BATCH files, but this works for me - there may be better ways of doing it...
#ECHO OFF
REM Combine images side-side pairwise from the current directory using ImageMagick
REM Images are assumed to be named file1.jpg, file2.jpg, file3.jpg
REM Images are resized to a common height, as specified on next line
SET HEIGHT=500
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /L %%A in (1,2,1000) DO (
SET /A "B=%%A+1"
SET _f1=file%%A.jpg
SET _f2=file!B!.jpg
IF NOT EXIST "!_f1!" GOTO BRK
IF NOT EXIST "!_f2!" GOTO BRK
SET _result=joined%%A_!B!.jpg
ECHO Joining !_f1! and !_f2! into !_result!
convert "!_f1!" "!_f2!" -resize x%HEIGHT% +append "!_result!"
)
:BRK
I have no idea how you do a while loop in Windows, so I am using a for loop. I am guessing you have no more than 1,000 files. If you do, increase the 1,000 on the third line. You can change the common height to which images are resized at the top of the script.
In general, if you want to lay out two images whose names do not fit your fileXYZ.jpg naming standard, let's say they are, imageA.jpg and imageB.jpg, beside each other and resize both to 500 pixels tall and save as result.jpg you would do
convert imageA.jpg imageB.jpg -resize x500 result.jpg

Related

Create fixed-size montage of images with missing files

Setting
Suppose we have a list of N elements of which an element can either be a path to an image (e.g. a.jpg) or NULL indicating that a file is missing.
Example (N = 6): a.jpg,NULL,c.jpg,NULL,NULL,f.jpg
All mentioned images (a.jpg, c.jpg, f.jpg) are guaranteed to have the same resolution.
Task
Create a fixed-width montage (e.g. out.jpg) in which NULL values are replaced with black images whose resolutions are consistent with the common resolution of a.jpg, c.jpg, f.jpg. I would like to abstain from creating an actual black.jpg and would prefer to create the image on-the-fly as needed.
Using ImageMagick's "montage" command, if your images are known dimensions so you can include that in the command, and if you can generate a text file "list.txt" of the image files and put "xc:black" on each line that has no image like this...
image00.png
image01.png
image02.png
image03.png
image04.png
xc:black
image06.png
image07.png
xc:black
xc:black
image10.png
image11.png
You can run the ImageMagick "montage" command something like this...
magick montage #list.txt -tile 3x4 -geometry 160x160+3+3! out.png
The "#" in front of the name of the text file tells IM to read the input images from there. The "-tile" describes how many columns and rows will be in the result. The "-geometry" setting is where you put the dimensions of the images and the spacing between columns and rows. The "xc:black" images are single black pixels, but the exclamation point forces them to the W and H dimensions in the "-geometry" argument.
That will create black images everywhere you have "xc:black" in the list. If you want to fill between the spaces with black also, add "-background black" to the command.
That works for me with IMv7 and "magick montage ..." For IMv6 you just use "montage". I'm pretty sure everything else about the command would work the same way.

How is the colon operator defined in the context of image magick command line usage

I can't find any documentation for this.
I have found examples in the image magick documentation which use a colon but nothing explicit about how the colon is interpreted.
The examples are confusing ;
magick -size 640x480 pattern:checkerboard checkerboard.png
suggests it sets the attribute on the left (pattern) to the value on the right (checkerboard)
but then
magick -size 640x480 -depth 8 rgb:image image.png
suggests it sets file type of image - the thing on the right - to what is left of it
EDIT
This was all just a brain fart on my part; I was thinking (for various reasons) of "image" as a thing being made/assigned rgb which makes no sense (as "image" is a file name / input parameter).
The sensible interpretation is obviously of rgb as a thing (image of type rgb) being assigned the info in the file "image" .
So from these two examples at least, it appears the colon just assigns/applies the right hand operand to the left hand operand as you would expect.
There are a couple of ways the colon is used.
Some options which create their own canvas have a colon, for example:
xc: creates a canvas
gradient:colourA-colourB creates a gradient from colourA to colourB
tile: creates a repeated tile
radial-gradient: creates a radial gradient
rose: creates the built-in rose image
pattern: for a built-in pattern as you saw
logo: for the ImageMagick logo
label: for text labels
caption: for text captions
Then the colon sometimes prefixes a filename to tell ImageMagick what is in it. This is your rgb: use case, and it is necessary because the filename doesn't happen to end in .rgb. Other examples of this are:
gray: when the greyscale input file doesn't end in .gray
tif:fd:5 read a TIFF from file descriptor 5
Or to tell it to write a specific variant of a file, e.g.:
PNG8: to write a palettised PNG
PNG24: to write an RGB888 PNG
PNG32: to write an RGBA8888 PNG with alpha
PTIF: to write a pyramid TIFF
BMP3: to write a version 3 Microsoft BMP file
fd:3 write output on file descriptor 3
gif:fd:4 write output as GIF on file descriptor 4
There is some documentation here.

Convert sprite sheet to gif animation

The frames go in the order left to right, top to bottom, the animations go sequentially, all frames are of the same size.
1234
5612
345
I need a command that would take frame size, coordinates of the first frame and frame count as input and give an animated gif as output. Preferably without generating intermediate files.
I could do this using a programming language, but isn't there a way to do it easier with a command line tool like ImageMagick or GraphicsMagick? It feels to me like it should be a common task, yet I've found only questions about how to convert gif to sprite sheet, not the other way around.
With ImageMagick you would extract each frame sub-image with -crop WxH +adjoin +repage, and then animate the frames together.
For example, given a sprite of 300x289 sub-images like the following...
convert sprite.png -crop 300x289 +adjoin +repage -adjoin -loop 0 -delay 1 output.gif
See Animation Basics, and Animation Modifications for other examples.
If you set variables in your shell for the width and height of an individual sprite, the X and Y offsets for the starting sprite, and the number of sprites to use, an ImageMagick command like this will extract the requested sprites from the sheet and turn them into an animated GIF.
This is in Windows CMD syntax...
set WIDE=100
set HIGH=100
set XCOORD=100
set YCOORD=300
set FRAMES=5
convert spritesheet.png ^
-set option:distort:viewport %[fx:%FRAMES%*%WIDE%]x%HIGH% ^
-set option:slider %[fx:%YCOORD%*(w/%WIDE%)+%XCOORD%] ^
-crop %WIDE%x%HIGH% +append +repage ^
-distort affine "%[slider],0 0,0" ^
-crop %WIDE%x%HIGH% +repage ^
-set delay 50 -loop 0 result.gif
The variables %WIDE% and %HIGH% are the dimensions of an individual sprite.
The variables %XCOORD% and %YCOORD% are the offsets of the first sprite you need from left and top of the sheet.
The variable %FRAMES% is the total number of sprites to extract.
The command starts by reading the input sheet. It uses the input image dimensions and your provided variables to define some settings for IM to use later. First is the dimensions of the viewport needed to isolate the requested number of sprites. Second, it calculates the offset where the first sprite will be after the sheet has been cropped into single sprites and appended into one horizontal row.
Next it "-crop"s the image into individual sprites and "+append"s them into a single horizontal row.
Then it uses "-distort affine" to slide the whole row of sprites the required distance – "%[slider]" – to the left, some amount out of the viewport if needed, and reduces the viewport to just show the proper number of sprites.
After that it crops that image into individual sprites again, sets a delay for the animation, and writes the output GIF.
For a Windows BAT script you'll need to double the percent signs "%%" on the IM variables and FX expressions, but not the shell variables like %WIDE%.
For a *nix shell or script you'll need to set those variables and access them differently. Also you'll need to replace the continued line carets "^" with backslashes "\".
For ImageMagick version 7 start the command with "magick" instead of "convert".
Before writing the output GIF you'll want to set your required dispose method, the delay, and probably "-loop 0".

How to remove white space between ImageMagick's montage tiles?

I current have code that build a montage using ImageMagick. This is my line of code:
montage -mode Concatenate -tile ${tile} -geometry ${geometry}+0+0 ${input} ${output}
I'm using -label ${label} to name my labels (in my input var).
This gets me a montage with a lot of white space, like that:
I checked on the manual and forums but everyone seem to agree that the way to do this is to use concatenate or geometry +0+0. I am already using those and it does not work. I also read that the font should be automatically chosen to fit the free space. Right now, there is way too much white space.
My goal: To get the white space (between the tiles on the vertical) to fit the current labels height and nothing more.
If you have an idea, I would be really happy.
Thank you anyway guys!
PS: It also doesn't work without labels. I get:
PPS: I'm sorry if my english is not really good, I am french from Montréal, Qc, Canada.
UPDATE: Those are my settings:
tile=4x3
geometry=386x305
The additional white space is coming from your geometry setting. The options -geometry 386x305+0+0 is adding an additional 15px between the image and the label.
If you omit the WxH and add a non-zero value to the offset -geometry +0+15, then you'll have additional white space after the label.
To limit the white space to text height, and nothing more, just keep the option as -geometry +0+0.
I also read that the font should be automatically chosen to fit the free space.
I think that's reversed. The white space is determined by the typeface of the font. I wouldn't say fonts automatically adjust <blank>, but default to <blank>. It's always a good idea to define the font & pointsize.

Remove shapes from image with X number of pixels or less

If I have a image with, let's say squares. Is it possible to remove all shapes formed by 10 (non white) pixels or less and keep all shapes that is formed by 11 pixels or more? I want to do it programmatically or with a command line.
Thanks in advance!
Possibly an algorithm called Erosion may be useful. It works on boolean images, shrinking all areas of "true" removing one layer of their surface pixels. Apply a few times, and small areas disappear, bigger ones remain (though shrunken). De-shrink the survivors with the opposite algorithm, dilation (apply erosion to the logical complement of the image). Find a way to define a boolean images by testing if a pixel is inside an "object" however you define it, and find a way to apply the results to the original image to change the unwanted small objects to the background color.
To be more specific would require seeing examples.
Look up flood fill algorithms and alter them to count the pixels instead of filling. Then if the shape is small enough, fill it with white.
There are a couple of ways to approach this. What you are referring to is commonly called Despeckle in Document Imaging Applications. Document scanners often introduce a lot of dirt and noise into an image during scanning and so this must be removed removed to help improve OCR accuracy.
I assume you are processing B/W images here or can convert your image to B/W otherwise it becomes a lot more complex. Despeckle is done by analysing all the blobs on the page. Another way to decide on blob size is to decide on width, height and number of pixels combined.
Leptonica.com - Is an Open Source C based library that has the blob analysis functions you require. With some simple check and loops you can delete these smaller objects. Leptonica can also be compiled quite easily into a command line program. There are many example programs and that is the best way to learn Leptionica.
For testing, you may want to try ImageMagick. It has a command line option for despeckle but it has no further parameters.
http://www.imagemagick.org/script/command-line-options.php#despeckle
The other option is to look for "despeckle" algorithms in Google.
ImageMagick, starting from version 6.8.9-10, includes a -connected-components option which can be used to do what you want, however from the example provided in the official website, it is not immediately obvious how to actually obtain the original image minus the removed connected components.
I'm almost sure there is a simpler way, but I did it via a clunky script performing a series of steps:
First, I ran the command from the connected components example:
convert in.png \
-define connected-components:verbose=true \
-connected-components 8 out.png
This produces output in the following format:
Objects (id: bounding-box centroid area mean-color):
(...)
181: 9x9+1601+916 1605.2,920.2 44 gray(0)
185: 5x5+1266+923 1268.0,925.0 13 gray(0)
274: 5x5+2276+1661 2278.0,1663.0 13 gray(255)
Then, I used awk to filter only the lines containing an area (in pixels) of black components (mean-color gray(0) in my image) smaller than my threshold $min_cc_area. Note that connected-components has an option to filter components smaller than a given area, but I needed the opposite. The awk line is similar to the following:
{if ($4 < $min_cc_area && $5=="gray(0)") { print $2 }}
I then proceeded to create a command-line for ImageMagick where I drew white rectangles on top of these connected components. The -draw command expects coordinates in the form x1,y1 x2,y2, so I used awk again to compute the coordinates from the ones in the format [w]x[h]+x1+y1 given by -connected-components:
awk '{print "white fill rectangle " $3 "," $4 " " $3+$1-1 "," $4+$2-1 }'
Finally, I ran the created ImageMagick command-line to create a new image combining all the white rectangles on top of the original one.
In the end, I got the following script:
# usage: $0 infile min_cc_area outfile
infile=$1
min_cc_area=$2
outfile=$3
awk_exp="{if (\$4 < $min_cc_area && \$5==\"gray(0)\") { print \$2 }}"
draw_rects=""
draw_rects+=$(convert $infile -define connected-components:verbose=true \
-connected-components 8 null: | \
awk "$awk_exp" | tr 'x+' ' ' | \
awk '{print " rectangle " $3 "," $4 " " $3+$1-1 "," $4+$2-1 }')
convert $infile -draw "fill white $draw_rects" $outfile
Note that this solution may erase black pixels near the removed CC's, if they insersect the bounding rectangle of the removed component.
You want a connected components labeling algorithm. It will scan through the image and give every connected shape an id number, as well as assign every pixel an id number of what shape it belongs to.
After running a connected components filter, just count the pixels assigned to each object, find the objects that have less than 10 pixels, and replace the pixels in those objects with white.
If you can use openCV, this piece of code does what you want (i.e., despakle). You can play w/ parameters of Size(3,3) in the first line to get rid of bigger or smaller noisy artifacts.
Mat element = getStructuringElement(MORPH_ELLIPSE, Size(3,3));
morphologyEx(image, image, MORPH_OPEN, element);
morphologyEx(image, image, MORPH_CLOSE, element);
You just want to figure out the area of each components. So an 8-direction tracking algorithm could help. I have an API solve this problem coded in C++. If you want, send me an email.

Resources