1

As mentioned in the title, I'm hoping to visualize my result in the appendix.enter image description here

where the red lines are drawn by programs given some specific degree angles. Is there a module in python that provide such functions? How can I do this?

PokeLu
  • 767
  • 8
  • 17

1 Answers1

1

As commentet the linked awnser Plot over an image background in python shows how to use matplotlib to plot simple geometrics over an existing image. If you want something more sophisticated (which also maybe changed over time) matplotlib would work but maybe will not perform as you want and includes a lot of code for all the element that you want to overlay.

Instead you should provide your overlay as an image and rotate it with opencv and the overlay the matrices.

I provide you a simple example:

Here we have the background Image:

enter image description here

We want to overlay the following circle:

enter image description here

and this cross, but rotated by 36 degree:

enter image description here

The following code will provide the wanted result:

enter image description here

import cv2
import numpy as np

def rotate_image(image, angle):
    image_center = tuple(np.array(image.shape[1::-1]) / 2)
    rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
    result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)
    return result

def overlay_images(img1, img2):
    if img1.shape[2] != 4 or img2.shape[2] != 4:
        print('png needs Alphachannel!')
        return 
    alpha_img1 = img1[:,:,3] / 255.0
    alpha_img2 = img2[:,:,3] / 255.0

    for color in range(0, 3):
        img1[:,:,color] = alpha_img2 * img2[:,:,color] + \
            alpha_img1 * img1[:,:,color] * (1 - alpha_img2)

        img1[:,:,3] = (1 - (1 - alpha_img2) * (1 - alpha_img1)) * 255
    return img1

img_bg = cv2.imread('img1.png',cv2.IMREAD_UNCHANGED)
img_circle = cv2.imread('img2.png',cv2.IMREAD_UNCHANGED)
img_cross = cv2.imread('img3.png',cv2.IMREAD_UNCHANGED)

img_rotate_36 = rotate_image(img_cross, 36)

img1_2 = overlay_images(img_bg, img_circle)
img1_2_3 = overlay_images(img1_2, img_rotate_36)

cv2.imwrite('img_rotated.png', img1_2_3)

cv2.imshow('Rotatet Image', img1_2_3)
cv2.waitKey(0)
cv2.destroyAllWindows()

The interesting part are the rotation and the overlay. I used for this situation for the overlay this solution https://stackoverflow.com/a/59211216/10985257 because the cv2.addWeighted function seems to have problems with alpha channel. The algorithm used is called alpha composition. The rotation is based on https://stackoverflow.com/a/9042907/10985257 and is simmple affine Transformation based on a rotary matrix. I put both application in a function in the code above.

MaKaNu
  • 762
  • 8
  • 25
  • 1
    Thanks a lot! I"ve already finished the job using matplotlib but this answer opens a new perspective. – PokeLu Jul 20 '20 at 13:12