Remove background, reflection and shadows with Image Magick - imagemagick

I have images where I would like to make the background transparent, remove the shadow and remove the product reflection.
So what I want to do is
Remove reflection
Remove shadow
Remove background
Test image

In Imagemagick 6, you can threshold the image and get the bounds of the black area. Then crop the original to those bounds.
convert image.png -threshold 50% +write image_thresh50.png -format "%#" info:
229x367+39+0
convert image.png -crop 229x367+39+0 +repage image_cropped.png
If using Imagemagick 7, change convert to magick.
Is this what you want?

To follow up on Bonzo's comment, in Unix ImageMagick 6, I could do:
cropvals=$(convert image.png -threshold 50% +write hAfUS_thresh50.png -format "%#" info:)
convert image.png -crop $cropvals +repage image_cropped.png
And in Unix, Imagemagick 7, I could do:
magick image.png \( +clone -threshold 50% -set option:cropvals "%#" +delete \) -crop "%[cropvals]" +repage image_cropped2.png
The reason I did not post these was because I did not know what OS/Platform the OP was using. It always helps when asking questions about Imagemagick to post its version and the platform it is run on.
Sorry I do not know how to do this in Windows syntax

Related

Imagemagick create image and place image inside with max size

I have trimmed .pngs and need them placed on a canvas (3000x3000 px) BUT with a max size.
convert -size 3000x30000 xc:transparent test.png -gravity south -composite -size 2200x2200 result.png
The code I have now works, but the sizing of the image is off. My canvas is 3000x3000px as intended, but the image placed on the canvas doesn't have the correct size. It should have a max width/height of 2200px and if possible be scaled up, if they are to small in height.
This ImageMagick command will resize the input image to 2200 pixels on the longer side while maintaining its aspect, then create a 3000x3000 transparent canvas, then swap the input image and the canvas, and finish by compositing the resized input image onto the transparent canvas...
convert input.png -resize 2200x2200 \
-size 3000x3000 xc:none +swap -gravity south -composite result.png
For Windows change that continued line backslash "\" to a caret "^". For ImageMagick v7 use "magick" instead of "convert".
Unix syntax:
convert -size 3000x30000 xc:transparent \( test.png -resize 2200x2200 \) -gravity south -composite result.png
Windows syntax:
convert -size 3000x30000 xc:transparent ( test.png -resize 2200x2200 ) -gravity south -composite result.png
Why not use -extent?
convert input.jpg -resize 2200x2200 -background none -gravity south -extent 3000x3000 result.png

How to split an image with a grid and preserve transparency bounding box

I have some png images that I want to split it into parts, like by grid or size.
But each part should have the same bounding box (transparency) as original image.
Example:
Splitting image into 2 parts.
Original: 200 × 89
Output:
part_1.png, 200 × 89
part_2.png, 200 × 89
Can ImageMagick do this? Or any other app or method.
My actual goal is to split into 100+ slices images.
EDIT:
Another goal to have an indents for each slice. Say indent = 10px.
Example:
Input: 200 x 100
Output:
part_1.png, 200 x 100
part_2.png, 200 x 100
And just as example, to visually compare input and output: combined output images in Photoshop as layer added one onto another
200 x 100 :
Also this is showing input image added onto combined(so it's better to see what was cropped and how):
In ImageMagick, you can split an image into many parts with the -crop command. For your example above with two parts, you can do that with the following commands. ImageMagick will append -0, -1 ... to the output file names.
ImageMagick 6:
dim=`convert image.png -format "%wx%h" info:`
convert \( -size $dim xc:none \) null: \( image.png -crop 50x100% \) -layers composite result.png
ImageMagick 7:
magick \( image.png -set option:dim "%wx%h" -crop 50x100% \) null: \( -size "%[dim]" xc:none \) -reverse -layers composite result.png
The results are:
See
http://www.imagemagick.org/Usage/crop/#crop
http://www.imagemagick.org/Usage/crop/#crop_percent
http://www.imagemagick.org/Usage/crop/#crop_tile
http://www.imagemagick.org/Usage/crop/#crop_quad
http://www.imagemagick.org/Usage/crop/#crop_equal
http://www.imagemagick.org/script/command-line-options.php#layers
Note that -crop keeps the virtual canvas information if you do not add +repage afterwards. So to put the individual images back into their original placement, you have to composite them onto a transparent background the size of the input. That is done in one command using -layers composite using the null: separator.
Here is another way to add transparent areas between parts of a crop in ImageMagick. Crop the image into pieces, chop off the parts you want to remove, then pipe to montage to add the spacing back.
Input:
Here I make this into a 4x4 grid of images with 10 pixel spacing:
convert lena.png -crop 25%x25% +repage -gravity east -chop 10x0 -gravity south -chop 0x10 +repage miff:- | montage - -background none -tile 4x4 -geometry +5+5 result.png
To answer your new question, you can do that with a script loop. On a Unix-like platform, assuming your images do not have spaces, you can do the following:
cd path/to/current_folder
list=`ls *.png`
for img in $list; do
name=`convert $img -format "%t" info:`
dim=`convert $img -format "%wx%h" info:`
convert \( -size $dim xc:none \) null: \( $img -crop 50x100% \) -layers composite -scene 1 path/to/new_folder/${name}_%d.png
done
If you want leading 0s in the output, say 3, use path/to/new_folder/${name}_%03d.png.
Note that to start with 1 rather than 0, I have added -scene 1.
Sorry, I do not know how to script for Windows.
Please always provide your ImageMagick version and platform.
In ImageMagick, the best way to put transparent areas into your image is with a binary mask that is put into the alpha channel of your image.
convert input.png \( -size 200x89 xc:white -size 10x89 xc:black -gravity center -composite \) -alpha off -compose copy_opacity -composite result.png
You can add as many blank areas as you want by adding more white areas to the mask or by tiling out one region of black and one region of white to create the mask with regular spacing of black and white.
Edited to add this ImageMagick 6 example which splits the input image into 4 pieces, 25% of the original width and 100% of its height, then creates a transparent canvas for each piece the same dimensions of the input image, and locates the pieces at their original offsets on those canvases.
convert input.png -set option:distort:viewport %[w]x%[h] -crop 25x100% \
-virtual-pixel none -distort affine "0,0 %[fx:s.page.x],%[fx:s.page.y]" out%03d.png
The output file names will be numbered starting from zero like "out000.png", etc.
Original message...
Here's a simple command using ImageMagick 7 that can crop an image into any number of pieces, and output all the pieces at their original offsets on transparent backgrounds of the original input dimensions...
magick input.png -crop 100x1# -background none \
-extent "%[fx:s.page.width]x%[fx:s.page.height]-%[fx:s.page.x]-%[fx:s.page.y]" out%03d.png
That "-crop 100x1#" tells it to split the image into a grid 100 pieces wide by 1 piece high. You could just as well specify the crop sizes as percents or numbers of pixels.
Edited again to add:
This following command will split the input image into the individual pieces specified with the "-crop" operator, then shave 5 pixels from every side of each piece, then apply a 5 pixel transparent border to every side of each piece. It will still remember the original locations of the pieces within the input canvas, so the "-distort affine ..." can extend the canvases and place the pieces where they were in the input image.
convert input.png -set option:distort:viewport %[w]x%[h] \
-bordercolor none -background none -virtual-pixel none \
-crop 25x100% -shave 5x5 -border 5x5 \
-distort affine "0,0 %[fx:s.page.x],%[fx:s.page.y]" out%03d.png
To use this command with IM7 you need to change "convert" to "magick".
Given the changes of requirements provided by Kamikaze, here is one way to achieve the split with indent in ImageMagick, assuming I understand correctly.
dim=`convert image.png -format "%wx%h" info:`
convert \( -size $dim xc:none \) null: \( image.png -crop 50x100% -shave 5x5 \) -geometry +5+5 -layers composite result.png
To check, I flatten over a blue background:
convert result-0.png result-1.png -background blue -flatten result.png

How to find out the average color (rgb) of masked area of an Image

I would like to get the average color in rgb of the mask area of a png image.
the following just outputs the average color of the whole image
convert demo.png -mask demo_mask.png -resize 1x1 txt:-
In ImageMagick, -scale 1x1! will ignore the transparent pixels and give you the average of the opaque pixels. So if you want the average of the masked region, you can put the mask into the alpha channel and then use -scale 1x1! to average it down to one pixel. The mask should be white where you want to get the average and black where it should be transparent and ignore those pixels in the average. So this should do it.
convert image.png mask.png -alpha off -compose copy_opacity -composite -scale 1x1! -alpha off -format "%[pixel:u.p{0,0}]" info:
For example if I make the logo: image transparent where it is white and then get the average, I get
convert logo: -transparent white -scale 1x1! -alpha off -format "%[pixel:u.p{0,0}]" info:
srgb(100,81,99)
You can show that this works, by doing it the long way. Multiply the mask by the image, then get the average of each channel of the product. Then get the average of the mask. Then compute the ratios scaled to the range 0 to 255.
convert logo: -transparent white logot.png
convert logot.png -alpha extract mask.png
declare `convert \( logot.png -alpha off \) mask.png -compose multiply -composite -format "IR=%[fx:mean.r]\nIG=%[fx:mean.g]\nIB=%[fx:mean.b]\n" info:`
echo "IR=$IR; IG=$IG; IB=$IB"
IR=0.0651798; IG=0.0529989; IB=0.0641607
MM=`convert mask.png -format "%[fx:mean]\n" info:`
echo "MM=$MM"
MM=0.165872
convert xc: -format "srgb(%[fx:round(255*$IR/$MM)],%[fx:round(255*$IG/$MM)],%[fx:round(255*$IB/$MM)])\n" info:
srgb(100,81,99)
Result is the same as above.
ASIDE: Note that
convert \( logot.png -alpha off \) mask.png -compose multiply -composite ...
in this case is the same as just
convert logot.png -alpha remove ...
But I show it the long way, if the user has a separate mask and image with no transparency.
You should be able to get very nearly what you want with a command something like this...
convert image.png mask.png -compose copyopacity -composite -resize 1x1! txt:-
To output only the color information you can try something like this...
convert image.png mask.png \
-compose copyopacity -composite -resize 1x1! -format "%[pixel:p]" info:
I haven't tried it, but you may have to "-negate" your mask image depending on which version of IM you're using because there have been changes in the way the alpha channel is handled.
You'll get a very slightly different result if you "-trim" before the "-resize".
If you don't want to output the alpha channel information, you can add "-alpha off" after the "-resize".
Perhaps...
convert demo.png -mask demo_mask.png -trim -fx mean -extent 1x1 txt:- |\
tail -1 | cut -d ' ' -f 4
This would work because -trim will reduce the masked image down to the MBR of the ROI. Fx operator -fx mean will convert all pixels into the overall average. And finally the -extent 1x1 will isolate the first pixel in the image. The rest is basic unix utilities.
Another option with better performance...
MEAN=$(convert demo.png -mask demo_mask.png -trim -format '%[fx:mean]' info:-)
convert null: -depth 8 -format "%[pixel:$MEAN]" info:-
Or from the Quantization documentation...
convert demo.png -mask demo_mask.png -trim -scale 1x1\! '%[pixel:s]' info:-

How to square an image and pad with transparency from the commandline (imagemagick)

The section entitled Square Padding or Cropping describes a method to generate a square image--for a file whose dimensions are unknown--and pad the background with a color.
How do I perform the same operation, but create a transparent background.
Let's make a red off-square image first, that is 300x200:
convert -size 300x200 xc:red image.png
Now let's put make a square image of it, but using a yellow background so you can see it:
convert -background yellow -gravity center image.png -resize 400x400 -extent 400x400 result.png
Now we can do the same thing again, but make the background transparent:
convert -background none -gravity center image.png -resize 400x400 -extent 400x400 result.png
and, just check to make sure it has worked:
identify result.png
result.png PNG 400x400 400x400+0+0 8-bit sRGB 418B 0.000u 0:00.000
These modified methods from Anthony's examples both work for me:
convert thumbnail.gif \
\( +clone -rotate 90 +clone -mosaic +level-colors grey -transparent grey \) \
+swap -gravity center -composite square_padded.gif
convert thumbnail.gif -virtual-pixel none -set option:distort:viewport \
"%[fx:max(w,h)]x%[fx:max(w,h)]-%[fx:max((h-w)/2,0)]-%[fx:max((w-h)/2,0)]" \
-filter point -distort SRT 0 +repage square_external.gif
A pure imagemagick command would be preferable, but here's a script that uses the 'file' unix/linux command to extract the dimensions of the file which can then be used on a resize to a square of the max dimension.
#!/usr/bin/env ruby
require 'shellwords'
def dims(image_escaped)
size_data = `file #{image_escaped}`
size_data[/, (\d+ x \d+),/, 1].split(' x ').map(&:to_i)
end
def square(image, pad_color='transparent')
image_esc = Shellwords.escape(image)
maxdim = dims(image_esc).max
geometry = "#{maxdim}x#{maxdim}"
# could use convert if don't want to clobber the image
system "mogrify -resize #{geometry} -background #{pad_color} -gravity center -extent #{geometry} -format png #{image_esc}"
end
ARGV.each do |image|
square(image)
end

Adaptive background after rotation/deskew in Imagemagick

After I rotate or deskew an image with Imagemagick there's a white background in the corners, where the rotation took place. Example:
convert image.png -rotate 10 out.png
Output: http://imgur.com/8bZQ6
Is there a way I could somehow fill up those white corners with some texture or at least a color that blends in with the image? Cropping is not an option.
I've found this great solution for simple rotation:
convert image.png -virtual-pixel Edge +distort SRT 10 out.png
Output: http://imgur.com/edMS0
But unfortunately it doesn't work with the -deskew command...
So, does anyone know how to fill up those corners in a similar way for the -deskew (and -rotate) command? The point is to mask the fact the image was rotated as best as possible.
I'll go ahead and answer my own question, but I'm still hoping for a better solution.
You can set the -background color, which works with rotate and deskew.
Here's a solution that uses the average image color:
convert image.png -background `convert image.png -resize 1x1 txt:- | tail -1 | cut -b 30-50` -rotate 10 out.png
Output: http://imgur.com/YCqkC
And a better solution that takes some border pixels:
convert image.png -background `convert image.png -resize 100x1! \( +clone -crop 1x1+0+0 \) +append -crop 2x1+99+0 -resize 1x1 txt:- | tail -1 | cut -b 30-50` -rotate 10 out.png
Output: http://imgur.com/4wDPO
There's some bash scripting (inside the backticks), so these solutions are unix only.
Try this:
convert image.png -background transparent -rotate 10 out.png

Resources