Find positions of transparent areas in images using PIL
<p>I want to fill transparent blocks in images by others images.
For example:
In this images we have 4 transparent blocks, witch need to fill.</p>

<p>Need to find positions of the blocks and determine x,y,x2,y2 coords so i will know how to resize the thumbnail to.</p>

<p><a href="https://i.stack.imgur.com/2pt93.png" rel="nofollow"><img src="https://i.stack.imgur.com/2pt93.png" alt="Image with transparent"></a></p>

<p>Someone know how i can do that using PIL, or maybe, unix tools.
Thanks for any help</p>

<p>You can do that at the command-line with <strong>ImageMagick</strong>, or in Python, Perl, PHP or C/C++.</p>

<p>First, extract the alpha channel:</p>

<pre><code>convert input.png -alpha extract alpha.png
</code></pre>

<p><a href="https://i.stack.imgur.com/eD04t.png" rel="nofollow"><img src="https://i.stack.imgur.com/eD04t.png" alt="enter image description here"></a></p>

<p>But I am going to do morphology and I want white on black, so invert it:</p>

<pre><code>convert input.png -alpha extract -negate alpha.png
</code></pre>

<p><a href="https://i.stack.imgur.com/R6ppT.png" rel="nofollow"><img src="https://i.stack.imgur.com/R6ppT.png" alt="enter image description here"></a></p>

<p>Now run a <em>"Connected Components"</em> analysis to find the blobs of white:</p>

<pre><code>convert input.png -alpha extract -negate -threshold 50% \
    -define connected-components:verbose=true           \
    -define connected-components:area-threshold=100     \
    -connected-components 8 -auto-level null:
</code></pre>

<p><strong>Output</strong></p>

<pre><code>Objects (id: bounding-box centroid area mean-color):
  0: 600x376+0+0 249.7,205.3 129723 srgb(0,0,0)
  2: 203x186+70+20 170.8,112.6 27425 srgb(255,255,255)
  1: 218x105+337+13 445.5,65.0 22890 srgb(255,255,255)
  4: 218x105+337+251 445.5,303.0 22890 srgb(255,255,255)
  3: 218x104+337+132 445.5,183.5 22672 srgb(255,255,255)
</code></pre>

<p>And there they are. Ignore the first row because it is black and corresponds to the whole image. Now, look at the second row and you can see the block is 203x186 at offset +70+20. The centroid is there too. Let me box that blob in in red:</p>

<pre><code>convert input.png -stroke red -fill none -draw "rectangle 70,20 272,205" z.png
</code></pre>

<p><a href="https://i.stack.imgur.com/BJS2k.png" rel="nofollow"><img src="https://i.stack.imgur.com/BJS2k.png" alt="enter image description here"></a></p>

python imagemagick python-imaging-library alpha pillow