Crop overlapping images with pillow
<p>I need help, please.
I'm trying to select and crop the overlapping area of two images with the Python Pillow library.</p>

<p>I have the upper-left pixel coordinate of the two pictures. With these, I can find out which one is located above the other.</p>

<p>I wrote a function, taking two images as arguments:</p>

<pre><code>def function(img1, img2):
    x1 = 223 #x coordinate of the first image
    y1 = 197 #y coordinate of the first image
    x2 = 255 #x coordinate of the second image
    y2 = 197 #y coordinate of the second image

    dX = x1 - x2
    dY = y1 - y2

    if y1 &lt;= y2: #if the first image is above the other
        upper = img1
        lower = img2
        flag = False
    else:
        upper = img2
        lower = img1
        flag = True

    if dX &lt;= 0: #if the lower image is on the left
        box = (abs(dX), abs(dY), upper.size[0], upper.size[1])
        a = upper.crop(box)
        box = (0, 0, upper.size[0] - abs(dX), upper.size[1] - abs(dY))
        b = lower.crop(box)
    else:
        box = (0, abs(dY), lower.size[0] - abs(dX), upper.size[1])
        a = upper.crop(box)
        box = (abs(dX), 0, lower.size[0], upper.size[1] - abs(dY))
        b = lower.crop(box)

    if flag:
        return b,a #switch the two images again
    else:
        return a,b
</code></pre>

<p>I know for sure that the result is wrong (It's a school assignment).
Thanks for your help.</p>

<p>First of all, I don't quite get what do you mean by one picture being "above" the other (shouldn't that be a z-position?), but take a look at this: <a href="http://stackoverflow.com/questions/20484942/how-to-make-rect-from-the-intersection-of-two">How to make rect from the intersection of two?</a> , the first answer might be a good lead. :)</p>

python pillow