Search code examples
pythonopencvimage-processingpython-imaging-librarymasking

How to join two alpha images horizontally and vertically?


I have created right-angle triangle images using alpha masks. I would like to join them vertically and horizontally. The masks:An alpha mask for right angle triangles

Another alpha mask for right angle triangles

The sliced images are: Right Angle Triangles using the first alpha mask

Right Angle Triangles using the second alpha mask

I would like to merge two right angle triangles in the following ways:

Desired Output

However,I have been an incorrect output: Incorrect output

I would like some guidance on how to approach this problem so that I can obtain the desired outputs.

The code for joining the triangles: I used the following example: Masking two images and merge into one image

def mirror_triangles_one():
  x=first_array[0] #The first array contains right angle triangles sliced using alpha mask one
  y=second_array[2] #The second array contains right angle triangles sliced using alpha mask two
  x_im=x
  x_im.paste(y, (-4, 0), y)
  x_im.save('mirror_five.png')
  return x_im

Original Image-Original Image


Solution

  • Here is how I would do it in Python/OpenCV/Numpy. But I had to crop your images, so the results will not be accurate. Assuming you have filled out the triangle images as rectangles with white, one simply hstack's the two images. Note that they must have the same heights.

    Left:

    enter image description here

    Right:

    enter image description here

    import cv2
    import numpy as np
    
    # read right image
    right = cv2.imread('right.png')
    rhh, rww = right.shape[:2]
    
    # read left image
    left = cv2.imread('left.png')
    lhh, lww = left.shape[:2]
    
    # compute min height and crop images to same height
    minh = min(rhh,lhh)
    right = right[0:minh, 0:rww]
    left = left[0:minh, 0:lww]
    
    # stack horizontally
    result = np.hstack([left,right])
    
    # save result
    cv2.imwrite('left_right_result.jpg', result)
    
    # display result
    cv2.imshow('result', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Result:

    enter image description here