Process image to find external contour

后端 未结 3 657
闹比i
闹比i 2020-12-18 07:50

I have hundreds of PNG images for which I have to generate corresponding B&W images that show the outer outline of the object. The source PNG image has alpha channel, so

3条回答
  •  忘掉有多难
    2020-12-18 08:45

    I would recommend ImageMagick which is available for free from here. It is included in many Linux distibutions anyway. It has Python, Perl ,PHP, C/C++ bindings available as well.

    I am just using it from the command-line below.

    convert donut.png -channel A -morphology EdgeOut Diamond +channel  -fx 'a' -negate output.jpg
    

    Basically, the -channel A selects the alpha (transparency) and applies the morphology to extract the outline of the opaque area. Then the +channel tells ImageMagick I am now addressing all channels again. The -fx is a custom function (operator) in which I set each pixel of the output image to a - the alpha value in the modified alpha channel.

    Edited

    The following may be quicker than using the above fx operator:

    convert donut.png -channel RGBA -separate -delete 0-2 -morphology EdgeOut Diamond -negate output.png
    

    Result:

    enter image description here

    If you have many hundreds (or thousands) of images to outline, I would recommend GNU Parallel, available from here. Then it will use all your CPU cores to get the job done quickly. Your command will look something like this - BUT PLEASE BACKUP FIRST and work on a copy till you get the hang of it!

    parallel convert {} -channel A -morphology EdgeOut Diamond +channel -fx 'a' -negate {.}.jpg ::: *.png
    

    That says to use everything after ::: as the files to process. Then in parallel, using all available cores, convert each PNG file and change its name to the corresponding JPEG file as the output filename.

提交回复
热议问题