[Python] How to save an image with transparency

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I start with an image that has transparent areas. I want to use perspective transform (see code below) and then save the result with imsave, savefig, or anything that works. I have no trouble saving the image, but I lose the transparency. How does one save the resultant image && retain transparency.

    import os
    import cv2 as cv
    import numpy as np
    import matplotlib.pyplot as plt

    def PerspectiveTransform():
    root = os.getcwd()

    imgPath = os.path.join(root, 'images/circle_grid3.png') # source image has transparent area
    img = cv.imread(imgPath)
    img = cv.cvtColor(img,cv.COLOR_BGR2RGBA)

    p1 = np.array([[0,0],[426,0],[0,426],[426,426]],dtype=np.float32)
    p2 = np.array([[0,0],[506,0],[68,873],[438,873]],dtype=np.float32)
    # array: topleft, topright, bottomleft, bottomright

    T = cv.getPerspectiveTransform(p1,p2)
    imgTrans = cv.warpPerspective(img,T,(506,873))

    plt.figure()

    plt.subplot(121)
    plt.imshow(img)
    plt.plot(p1[:,0],p1[:,1],'g.')

    plt.subplot(122)
    plt.imshow(imgTrans)
    plt.plot(p2[:,0],p2[:,1],'r.')


    plt.savefig('chart8.tiff', dpi=300, transparent=True)
    plt.imsave('source8.png', img, dpi=300, format="png")
    plt.imsave('destination8.tiff', imgTrans, dpi=300, format="tiff")
    plt.imsave('destination8.png', imgTrans, dpi=300, format="png")


    plt.show()

    if __name__ == '__main__':
    PerspectiveTransform()


    imsave() does not expect keyword argument 'transparent'. savefig() gives a transparent background, but not in the figures/

    Continue reading...

Compartilhe esta Página