使用 OpenCV 讀取影像並在 Tkinter 中顯示
OpenCV 是一個開源的 Python 計算機視覺庫,廣泛用於人工智慧和機器學習的研究。像 OpenCV 這樣的計算機視覺庫處理影像處理。我們可以使用 OpenCV 讀取影像,並進一步用於開發。
假設我們想要建立一個應用程式,該應用程式使用 OpenCV 讀取影像並在視窗中顯示它。
使用以下命令安裝 OpenCV:
pip install opencv-python
接下來,按照以下步驟操作:
在環境中安裝 OpenCV,並使用 **import cv2** 匯入庫。
匯入 **NumPy** 和 **PIL**(Pillow 包)用於影像計算。
使用 **imread(image_location)** 函式載入影像。
使用 **split(image)** 函式拆分影像的 RGB 顏色。
使用 **merge(rgb)** 函式合併影像顏色。
將多維矩陣轉換為影像。
使用 **PhotoImage(image= file)** 函式轉換給定的影像。
初始化一個標籤並顯示影像。
示例
#Import the tkinter library from tkinter import * import numpy as np import cv2 from PIL import Image, ImageTk #Create an instance of tkinter frame win = Tk() win.geometry("700x550") #Load the image img = cv2.imread('tutorialspoint.png') #Rearrange colors blue,green,red = cv2.split(img) img = cv2.merge((red,green,blue)) im = Image.fromarray(img) imgtk = ImageTk.PhotoImage(image=im) #Create a Label to display the image Label(win, image= imgtk).pack() win.mainloop()
輸出
執行以上程式碼將在視窗中載入並顯示影像。
確保影像“**tutorialspoint.png**”與程式位於同一資料夾中。
廣告