Home>

I'm trying to reverse the image loaded on tkinter

Problem i am experiencing

After reversing the image, after converting from BGR → RGB → PIL format → ImageTk format to display with tkinter, the transparent part is no longer transparent

Applicable source code
import tkinter
import cv2
from PIL import Image, ImageTk
root = tkinter.Tk ()
image_bgr = cv2.imread ('Image.png', cv2.IMREAD_UNCHANGED)
yAxis = cv2.flip (image_bgr, 1) #where image flipping with OpenCV
cv2.imwrite ('yAxis-reflect.png', yAxis) #Output image for confirmation-transparent parts are still transparent
image_rgb = cv2.cvtColor (yAxis, cv2.COLOR_BGR2RGB) # Since imread is BGR, convert to RGB
image_pil = Image.fromarray (image_rgb) # Convert from RGB to PIL format
image_tk = ImageTk.PhotoImage (image_pil) # Convert to ImageTk format
canvas = tkinter.Canvas (root, bg = "white", width = 400, height = 350) # Create Canvas
canvas.pack ()
canvas.create_image (0, 0, image = image_tk, anchor = 'nw') # ImageTk image layout
root.mainloop ()

Because the transparent part is no longer transparent after image inversion
I tried to put Image.putalpha () that transmits the image with PIL between various places, but I was not detailed about PIL, so it was useless

Supplemental information

Refer to this page for how to invert the image ・ Display the image edited with OpenCV with tkinter

How to flip images with OpenCV
http://peaceandhilightandpython.hatenablog.com/entry/2016/01/08/000857

How to display OpenCV images on tkinter
https://qiita.com/[email protected]/items/bc56441e80b3ccd5b2a4

  • Answer # 1

    import tkinter
    import cv2
    from PIL import Image, ImageTk
    root = tkinter.Tk ()
    image_bgr = cv2.imread ('Image.png', cv2.IMREAD_UNCHANGED)
    yAxis = cv2.flip (image_bgr, 1) #where image flipping with OpenCV
    cv2.imwrite ('yAxis-reflect.png', yAxis) #Output image for confirmation-transparent parts are still transparent at this point
    image_rgb = cv2.cvtColor (yAxis, cv2.COLOR_BGR2RGBA) # Since imread is BGR, convert to RGB
    image_pil = Image.fromarray (image_rgb) # Convert from RGB to PIL format
    image_tk = ImageTk.PhotoImage (image_pil) # Convert to ImageTk format
    canvas = tkinter.Canvas (root, bg = "white", width = 400, height = 350) # Create Canvas
    canvas.pack ()
    canvas.create_image (0, 0, image = image_tk, anchor = 'nw') # ImageTk image layout
    root.mainloop ()

    image_rgb = cv2.cvtColor (yAxis, cv2.COLOR_BGR2RGB)
    image_rgb = cv2.cvtColor (yAxis, cv2.COLOR_BGR2RGBA)

    Yes, Q71 who commented! m (_ _) m