Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đọc ảnh OpenCV và hiển thị trên Tkinter

OpenCV (cv2) đọc ảnh, chuyển RGB, dùng PIL/Pillow chuyển thành PhotoImage hiển thị trên Tkinter Label.

Các bước

  1. Cài OpenCV: pip install opencv-python
  2. Import cv2, numpy, PIL.
  3. Đọc ảnh: imread().
  4. Tách/kết hợp kênh màu BGR→RGB: split(), merge().
  5. Chuyển mảng thành Image: Image.fromarray().
  6. Tạo PhotoImage: ImageTk.PhotoImage().
  7. Hiển thị trên Label.

Ví dụ

# Import thư viện
from tkinter import *
import numpy as np
import cv2
from PIL import Image, ImageTk

# Tạo khung
win = Tk()
win.geometry("700x550")

# Đọc ảnh
img = cv2.imread('tutorialspoint.png')

# Sắp xếp lại kênh màu BGR -> RGB
blue, green, red = cv2.split(img)
img = cv2.merge((red, green, blue))

im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)

# Hiển thị
Label(win, image=imgtk).pack()

win.mainloop()

Kết quả

Hiển thị ảnh tutorialspoint.png trong cửa sổ Tkinter.

Đọc ảnh OpenCV và hiển thị trên Tkinter

Đảm bảo file ảnh cùng thư mục với code.