tk_png_image.py

#! /usr/bin/python3
# ==================================================================
# Display a PNG image using Tk
#
# 1. use OpenCV to read in an PNG image
# 2. create a canvas the size of the image
# 3. use PIL.ImageTk to convert the CV image to a Tk PhotoImage
# 4. add the PhotoImage image to the Tk canvas
# 5. Tk main loop - make everything visible
#
# Note: You must install a lot of "stuff" to read an image and
#       conversion. See the information in the next section.
#
# ------------------------------------------------------------------
#
# ---- code based on (I made some small changes)...
#
# solarianprogrammer.com/2018/04/20/
#                   python-opencv-show-image-tkinter-window/
#
# ---- Install OpenCV for Python3
#
# sudo pip3 install opencv-python
#
# From: solarianprogrammer.com/2018/04/25/
#       install-numpy-scipy-matplotlib-opencv-python-ubuntu/
#
# ---- Install PIL.ImageTk
#
# If you are using Python 3 + Pillow on Ubuntu,the package name
# is python3-pil.imagetk
#
# sudo apt-get python3-pil.imagetk
#
# For Python 2.7
#
# sudo apt-get python-pil.imagetk
#
# ------------------------------------------------------------------
#
# ---- Notes/Questions
#
# a. The displayed image colors are not correct.
#    This needs to be investigated.
#
# b. if the image is too big for the canvas, how do I resize
#    the image to what I need?
#
# ==================================================================

import tkinter as tk
import cv2
import PIL.Image, PIL.ImageTk

# create a window
window = tk.Tk()

# load an image using OpenCV
images = ["ring1.png","ring2.png","test1.png"]
cv_img = cv2.imread(images[0])
##cv_img = cv2.imread(images[1])
##cv_img = cv2.imread(images[2])

# get the image dimensions (OpenCV stores images as NumPy ndarray)
height, width, no_channels = cv_img.shape

#print(cv_img.shape)

str = "Width      : {}\n" + \
      "Height     : {}\n" + \
      "No_channels: {}\n" + \
      "dtype      : {}"

print(str.format(width,height,no_channels,cv_img.dtype))

# create a canvas that can fit the image
canvas = tk.Canvas(window,width=width,height=height)
canvas.pack()

# use PIL (Pillow) to convert the NumPy ndarray to PhotoImage
photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))

# add a PhotoImage to the canvas
canvas.create_image(0,0,image=photo,anchor=tk.NW)

# window main loop
window.mainloop()