làm Phương pháp phát hiện cạnh:
Kernel, Sobel, Laplacian, Canny, chuyển động mờ Blur, Enbossing
python
Assistant
Dưới đây là phương pháp sử dụng thư viện OpenCV trong Python để áp dụng các phương pháp phát hiện cạnh bạn đã liệt kê, bao gồm kernel tùy chỉnh, Sobel, Laplacian, Canny, làm mờ hình ảnh (Blur), và Embossing.
Đầu tiên, bạn cần cài đặt thư viện OpenCV nếu chưa có:
bash
pip install opencv-python
Sau khi cài đặt, bạn có thể sử dụng các đoạn mã Python dưới đây để áp dụng từng phương pháp:
1. Kernel
python
import cv2
import numpy as np
# Đọc ảnh vào
image = cv2.imread('image.jpg', 0) # 0 để đọc ảnh dưới dạng grayscale
# Khởi tạo kernel tùy chỉnh
kernel = np.array([[1, 0, -1],
[0, 0, 0],
[-1, 0, 1]])
# Áp dụng phép toán convolve
edges = cv2.filter2D(image, -1, kernel)
# Hiển thị ảnh
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. Sobel
python
import cv2
# Đọc ảnh vào
image = cv2.imread('image.jpg', 0)
# Áp dụng Sobel X
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0)
# Áp dụng Sobel Y
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1)
# Kết hợp cả hai
sobel_combined = cv2.bitwise_or(sobel_x, sobel_y)
cv2.imshow('Sobel X', sobel_x)
cv2.imshow('Sobel Y', sobel_y)
cv2.imshow('Sobel Combined', sobel_combined)
cv2.waitKey(0)
cv2.destroyAllWindows()
Trong các mã trên, bạn cần thay thế 'image.jpg' bằng đường dẫn tới ảnh bạn muốn sử dụng. Khi chạy mỗi đoạn code, bạn sẽ thấy hiệu ứng mà mỗi phương pháp tạo ra. Hãy đảm bảo rằng bạn đang làm việc trong môi trường có GUI hỗ trợ hiển thị cửa sổ hình ảnh của OpenCV.
User
cho vào cùng một chương trình và tạo giao diện màu mè hiệu quả
Assistant
Để tạo một chương trình Python có GUI cho việc so sánh các phương pháp phát hiện cạnh với giao diện màu mè và hiệu quả, chúng ta có thể sử dụng thư viện Tkinter cho giao diện và OpenCV cho xử lý ảnh. Dưới đây là một ví dụ cơ bản về cách thực hiện điều này:
Để bắt đầu, chúng ta cần cài đặt các thư viện cần thiết (nếu bạn chưa cài đặt OpenCV):
bash
pip install opencv-python
Tiếp theo, đây là một đoạn mã Python mẫu để tạo GUI:
python
User
để ảnh không bị thiếu và để cố định nó và để ảnh đã sửa và ảnh gốc riêng
Assistant
Để hiển thị ảnh gốc và ảnh đã qua xử lý cạnh trên cùng một giao diện mà không bị mất dữ liệu ảnh và giữ cho kích thước cố định, bạn có thể sử dụng các bước sau:
Khi đọc ảnh, lưu ảnh gốc vào một biến khác để không làm thay đổi nó khi áp dụng các bộ lọc.
Đặt kích thước cố định cho các panel hiển thị ảnh để tránh bị thay đổi kích thước mỗi khi cập nhật ảnh mới.
Hiển thị ảnh đã qua xử lý và ảnh gốc cạnh nhau trên hai panel riêng biệt.
Cải tiến đoạn mã trước để phản ánh các yêu cầu này như sau:
python
User
thấy mỗi buttom không thấy ản
Assistant
Đảm bảo rằng bạn đã cài đặt thư viện Pillow, cần thiết để chuyển đổi ảnh từ OpenCV sang Tkinter:
bash
pip install pillow
Sau đó đây là một phiên bản cải tiến của đoạn mã trên để xử lý việc hiển thị ảnh:
python
User
Traceback (most recent call last):
File "D:\Application\Python\Lib\tkinter_init_.py", line 1948, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 75, in open_image
process_image('original')
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 13, in process_image
img_gray = cv2.cvtColor(image_original, cv2.COLOR_BGR2GRAY)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:196: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Assistant
Lỗi này xuất phát từ việc cv2.cvtColor được gọi trên một ảnh rỗng hoặc không tồn tại, có nghĩa là hàm cv2.imread không thành công trong việc đọc ảnh từ đường dẫn bạn đã cung cấp hoặc người dùng đã đóng cửa sổ chọn file mà không chọn ảnh nào cả.
Để giải quyết vấn đề này:
Kiểm tra xem file đã được chọn thành công không bằng cách kiểm tra xem biến path có rỗng không trước khi tiếp tục xử lý.
Kiểm tra xem cv2.imread có đọc thành công không bằng cách kiểm tra xem ảnh image_original có rỗng không.
Cập nhật hàm open_image và process_image theo cách sau:
python
# Function to open file dialog and load an image
def open_image():
global path, image_original, image_original_tk, panelA, panelB
path = filedialog.askopenfilename()
if not path:
print("No image selected")
return
image_original = cv2.imread(path)
if image_original is None:
print("Invalid image path")
return
process_image('original')
# Function to load and process image
def process_image(filter_type):
global image, image_original, panelA, panelB, path
# If there is no image, return
if image_original is None:
print("No image to process")
return
# The rest of the code remains unchanged...
Thêm hai dòng kiểm tra này sẽ giúp tránh lỗi khi không có hình ảnh để xử lý và thông báo cho người dùng nếu có vấn đề. Kiểm tra lại đường dẫn đến ảnh và đảm bảo nó là một đường dẫn hợp lệ và hình ảnh không bị hỏng. Chú ý rằng nếu người dùng chọn "Cancel" trên cửa sổ chọn file thì không nên cố gắng xử lý ảnh.
User
không tôi bị lỗi Traceback (most recent call last):
File "D:\Application\Python\Lib\tkinter_init_.py", line 1948, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 75, in open_image
process_image('original')
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 40, in process_image
processed_image_pil = processed_image_pil.resize((basewidth, hsize), Image.ANTIALIAS)
^^^^^^^^^^^^^^^
AttributeError: module 'PIL.Image' has no attribute 'ANTIALIAS'
Assistant
Lỗi AttributeError: module 'PIL.Image' has no attribute 'ANTIALIAS' xảy ra do thư viện Pillow-trong các phiên bản mới đã loại bỏ thuộc tính ANTIALIAS như một hằng số riêng lẻ. Nếu bạn đang sử dụng một phiên bản mới của Pillow, bạn sẽ cần sử dụng Image.Resampling.LANCZOS thay thế, đây là tên mới cho cùng một phương pháp lấy mẫu.
Đổi Image.ANTIALIAS thành Image.Resampling.LANCZOS như dưới đây:
Bằng cách này, nếu Image.Resampling.LANCZOS không tồn tại (với các phiên bản cũ của Pillow), chương trình sẽ sử dụng Image.ANTIALIAS thay thế.
Hãy cập nhật đoạn mã này trong hàm process_image của bạn và điều này sẽ giải quyết lỗi bạn đang gặp phải.
User
nó không cập nhật panelA khi open ảnh khcas
Assistant
Vấn đề có thể xảy ra nếu panelA chỉ được khởi tạo một lần và bạn không cập nhật hình ảnh khi ảnh mới được mở. Để đảm bảo rằng hình ảnh mới được cập nhật đúng cách trong panelA, bạn cần cập nhật hình ảnh trong panel mỗi khi một tệp mới được chọn.
Đây là một cách để sửa đoạn mã và cập nhật panelA:
python
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
# Thêm biến toàn cục cho panelA và panelB
panelA = None
panelB = None
# Function to update the image panels
def update_panels(original_image_tk, processed_image_tk):
global panelA, panelB
if panelA is None or panelB is None:
# Create the initial panels
panelA = tk.Label(image=original_image_tk)
panelA.image = original_image_tk
panelA.pack(side="left", padx=10, pady=10)
panelB = tk.Label(image=processed_image_tk)
panelB.image = processed_image_tk
panelB.pack(side="right", padx=10, pady=10)
else:
# Update the panels
panelA.configure(image=original_image_tk)
panelA.image = original_image_tk
panelB.configure(image=processed_image_tk)
panelB.image = processed_image_tk
# Function to process and update images
def process_image(filter_type):
global image_original, path, root
if path:
# Convert image for display
original_image_tk, processed_image_tk = convert_image(image_original, filter_type)
# Update the image panels
update_panels(original_image_tk, processed_image_tk)
# Hàm này giống như trong ví dụ trước nhưng đã thêm phần update panelA khi tải ảnh mới
def open_image():
global path, image_original, panelA
path = filedialog.askopenfilename()
if not path:
return
image_original = cv2.imread(path)
if image_original is None:
return
process_image('original')
# Convert and resize the image for Tkinter, split from `process_image()` for clarity
def convert_image(image_cv2, filter_type):
img_gray = cv2.cvtColor(image_cv2, cv2.COLOR_BGR2GRAY)
if filter_type == 'sobel':
# Sobel filter code...
pass
elif filter_type == 'laplacian':
# Laplacian filter code...
pass
elif filter_type == 'canny':
# Canny filter code...
pass
# Add additional filters or the 'original' case
# Convert the original and processed images for Tkinter
original_image_pil = Image.fromarray(cv2.cvtColor(image_cv2, cv2.COLOR_BGR2RGB))
processed_image_pil = Image.fromarray(cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB))
# Resize the images to fit the panel
# You should add your own resizing code with the correct aspect ratio and size
# Convert the PIL images to ImageTk format
original_image_tk = ImageTk.PhotoImage(original_image_pil)
processed_image_tk = ImageTk.PhotoImage(processed_image_pil)
return original_image_tk, processed_image_tk
# Và cuối cùng khởi chạy GUI như bình thường...
User
tôi cần đầy đủ
Assistant
Để có một chương trình đầy đủ với khả năng cập nhật ảnh gốc và ảnh đã xử lý khi mở ảnh mới, sau đây là mã Python đầy đủ sử dụng Tkinter và OpenCV:
python
User
cv2.error: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'cvtColor'
Overload resolution failed:
src is not a numpy array, neither a scalar
Expected Ptrcv::UMat for argument 'src'
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Application\Python\Lib\tkinter_init_.py", line 1948, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 95, in
btn = tk.Button(root, text=text, command=lambda f=filter_type: process_image(f))
^^^^^^^^^^^^^^^^
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 20, in process_image
img_gray = cv2.cvtColor(image_original, cv2.COLOR_BGR2GRAY)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cv2.error: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'cvtColor'
Overload resolution failed:
src is not a numpy array, neither a scalar
Expected Ptrcv::UMat for argument 'src'
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\Application\Python\Lib\tkinter_init_.py", line 1948, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 95, in
btn = tk.Button(root, text=text, command=lambda f=filter_type: process_image(f))
^^^^^^^^^^^^^^^^
File "D:\Tailieuhoctap\thi giac may tinh\b_1_15.1\b1ver2.py", line 20, in process_image
img_gray = cv2.cvtColor(image_original, cv2.COLOR_BGR2GRAY)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cv2.error: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'cvtColor'
Overload resolution failed:
src is not a numpy array, neither a scalar
Expected Ptrcv::UMat for argument 'src'
Assistant
Lỗi này chỉ ra rằng cv2.cvtColor đã được gọi với một đối tượng không phải là một mảng NumPy (hoặc một scalar), điều này trái với kỳ vọng của OpenCV.
Nguyên nhân gốc của lỗi này nằm ở việc image_original có thể đã bị biến đổi từ một mảng NumPy sang một đối tượng khác (ví dụ: ImageTk.PhotoImage) trước khi chuyển vào hàm cv2.cvtColor. Điều này thường xảy ra vì sau khi image_original được chuyển đổi thành định dạng ImageTk.PhotoImage để hiển thị trong panelA, biến image_original không còn giữ được dữ liệu ảnh ban đầu.
Để sửa lỗi này, bạn cần giữ lại một bản sao riêng của ảnh gốc dưới dạng mảng NumPy và chỉ sử dụng bản sao đó cho các thao tác của OpenCV. Mã dưới đây đã được chỉnh sửa để chỉ rõ việc quản lý ảnh gốc:
python
# Khai báo biến toàn cục
panelA = None
panelB = None
image_cv = None
def process_image(filter_type):
global image_cv, panelA, panelB
# Kiểm tra xem ảnh có tồn tại không
if image_cv is None:
return
# Chuyển ảnh gốc về dạng grayscale
img_gray = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY)
# ... tiếp tục với các bộ lọc cụ thể...
def open_image():
global image_cv, panelA, panelB
# Mở cửa sổ dialog để chọn ảnh
path = filedialog.askopenfilename()
if len(path) > 0:
# Load ảnh gốc vào biến image_cv
image_cv = cv2.imread(path)
# Chuyển đổi ảnh gốc sang định dạng Tkinter
image_display = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)
image_display = Image.fromarray(image_display)
image_display = ImageTk.PhotoImage(image_display)
# Cập nhật panelA với ảnh gốc
if panelA is None:
panelA = tk.Label(image=image_display)
panelA.pack(side="left", padx=10, pady=10)
else:
panelA.configure(image=image_display)
panelA.image = image_display
# Mặc định hiển thị ảnh gốc trong panelB sau khi mở
process_image('original')
Trong đoạn mã sửa đổi này:
Biến image_cv được dùng để lưu ảnh dạng mảng NumPy, và được cập nhật khi mở ảnh mới.
Sau mỗi lần mở ảnh mới, image_cv sẽ giữ mảng NumPy của ảnh, trong khi bản đồ hóa Tkinter của ảnh sẽ được lưu vào biến cục bộ để hiển thị.
Trong hàm process_image, chỉ image_cv mới được dùng để làm việc với OpenCV.
Lưu ý: Khi bạn chỉnh sửa mã, đảm bảo rằng mọi biến được sử dụng đều đúng với mục đích của nó và không bị ghi đè một cách ngoài ý muốn.
User
cố định ảnh import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np # Thêm thư viện numpy
Function to load and process image
def process_image(filter_type):
global image, panelA, path
code
if path:
# Load the image and convert it to grayscale
image = cv2.imread(path, 0)
if filter_type == 'sobel': # Sửa dấu nháy đơn ở đây
sobelX = cv2.Sobel(image, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(image, cv2.CV_64F, 0, 1)
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
processed_image = sobelCombined
elif filter_type == 'laplacian': # Sửa dấu nháy đơn ở đây
processed_image = cv2.Laplacian(image, cv2.CV_64F)
elif filter_type == 'canny': # Sửa dấu nháy đơn ở đây
processed_image = cv2.Canny(image, 100, 200)
elif filter_type == 'blur': # Sửa dấu nháy đơn ở đây
processed_image = cv2.GaussianBlur(image, (5, 5), 0)
elif filter_type == 'embossing': # Sửa dấu nháy đơn ở đây
kernel = np.array([[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]])
processed_image = cv2.filter2D(image, -1, kernel)
else: # original
processed_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Convert the image to PIL format and then to ImageTk format
processed_image = Image.fromarray(processed_image)
processed_image = ImageTk.PhotoImage(processed_image)
# If the panel A is None, initialize it
if panelA is None:
panelA = tk.Label(image=processed_image)
panelA.image = processed_image
panelA.pack(side="left", padx=10, pady=10)
else: # Update the panel
panelA.configure(image=processed_image)
panelA.image = processed_image
Assistant
Để cố định kích thước ảnh trong giao diện Tkinter (để nó không thay đổi kích cỡ mỗi khi bạn mở ảnh mới hoặc áp dụng bộ lọc khác nhau), bạn cần áp dụng một số thay đổi vào chương trình của bạn. Một cách tiếp cận có thể là resize ảnh đầu vào về kích cỡ cố định trước khi hiển thị nó.
Đây là đoạn mã đầy đủ với những cải tiến để cố định kích thước ảnh:
python
User
khi nhấn nút open thì mới cho chọn các tùy chọn sửa ảnh và cố định ảnh là 600x600
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
Set a fixed display size for the images
display_size = (300, 300)
Global variables
image_original = None
panelA = None
path = None
Function to load and process image
def process_image(filter_type):
global image_original, panelA
code
if image_original is not None:
# Resize the image to fit the display size
image_resized = cv2.resize(image_original, display_size, interpolation=cv2.INTER_AREA)
if image_resized.ndim == 3 and filter_type != 'original':
# Convert to grayscale for filtering if needed
image_resized = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)
# Apply the specified filter
if filter_type == 'sobel':
sobelX = cv2.Sobel(image_resized, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(image_resized, cv2.CV_64F, 0, 1)
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
processed_image = sobelCombined
elif filter_type == 'laplacian':
processed_image = cv2.Laplacian(image_resized, cv2.CV_64F)
elif filter_type == 'canny':
processed_image = cv2.Canny(image_resized, 100, 200)
elif filter_type == 'blur':
processed_image = cv2.GaussianBlur(image_resized, (5, 5), 0)
elif filter_type == 'embossing':
kernel = np.array([[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]])
processed_image = cv2.filter2D(image_resized, -1, kernel)
else: # 'original'
processed_image = image_resized
if processed_image.ndim == 2:
# Convert to BGR for color consistency
processed_image = cv2.cvtColor(processed_image, cv2.COLOR_GRAY2BGR)
# Convert the image to PIL format and then to ImageTk format
processed_image = Image.fromarray(processed_image)
processed_image = ImageTk.PhotoImage(processed_image)
# If the panel A is None, initialize it
if panelA is None:
panelA = tk.Label(image=processed_image)
panelA.image = processed_image
panelA.pack(side="left", padx=10, pady=10)
else: # Update the panel
panelA.configure(image=processed_image)
panelA.image = processed_image
Assistant
To achieve the functionality where the filter options (buttons) only become available after opening an image, and to set the display image size to 600x600, you can disable the buttons initially and then enable them once an image is opened. Also, display_size should be set to (600, 600). Here is the revised code:
python
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
# Set a fixed display size for the images
display_size = (600, 600)
# Global variables
image_original = None
panelA = None
buttons = []
# Function to load and process image
def process_image(filter_type):
# Your existing process_image function with the fixed display_size (600, 600)
# ...
# Function to open file dialog and load an image
def open_image():
global path, image_original, panelA
path = filedialog.askopenfilename()
if path:
image_original = cv2.imread(path)
# Resize the image to the display size for consistency
image_resized = cv2.resize(image_original, display_size, interpolation=cv2.INTER_AREA)
image_display = Image.fromarray(cv2.cvtColor(image_resized, cv2.COLOR_BGR2RGB))
image_original_tk = ImageTk.PhotoImage(image_display)
if panelA is None:
panelA = tk.Label(image=image_original_tk)
panelA.pack(side="left", padx=10, pady=10)
else:
panelA.configure(image=image_original_tk)
panelA.image = image_original_tk
# Enable the buttons once an image is successfully opened
for button in buttons:
button['state'] = 'normal'
# Function to exit the application
def exit_application():
root.destroy()
# Initialize the window
root = tk.Tk()
root.title("Edge Detection GUI")
# Create open button for loading images
btn_open = tk.Button(root, text="Open Image", command=open_image)
btn_open.pack(side="top", fill="both", expand="yes", padx=10, pady="10")
# Create buttons for different edge detection methods
methods = ['sobel', 'laplacian', 'canny', 'blur', 'embossing']
for method in methods:
btn = tk.Button(root, text=method.title(), command=lambda m=method: process_image(m), state='disabled')
btn.pack(side="top", fill="both", expand="yes", padx=10, pady="10")
buttons.append(btn) # Add buttons to the list
# Create exit button
btn_exit = tk.Button(root, text="Exit", command=exit_application)
btn_exit.pack(side="bottom", fill="both", expand="yes", padx=10, pady="10")
# Start the GUI loop
root.mainloop()
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
# Function to load and process image
def process_image(filter_type):
global image, panelA, path
if path:
# Load the image and convert it to grayscale
image = cv2.imread(path, 0)
if filter_type == 'sobel':
sobelX = cv2.Sobel(image, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(image, cv2.CV_64F, 0, 1)
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
processed_image = sobelCombined
elif filter_type == 'laplacian':
processed_image = cv2.Laplacian(image, cv2.CV_64F)
elif filter_type == 'canny':
processed_image = cv2.Canny(image, 100, 200)
elif filter_type == 'blur':
processed_image = cv2.GaussianBlur(image, (5, 5), 0)
elif filter_type == 'embossing':
kernel = np.array([[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]])
processed_image = cv2.filter2D(image, -1, kernel)
else: # original
processed_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Convert the image to PIL format and then to ImageTk format
processed_image = Image.fromarray(processed_image)
processed_image = ImageTk.PhotoImage(processed_image)
# If the panel A is None, initialize it
if panelA is None:
panelA = tk.Label(image=processed_image)
panelA.image = processed_image
panelA.pack(side="left", padx=10, pady=10)
else: # Update the panel
panelA.configure(image=processed_image)
panelA.image = processed_image
# Function to open file dialog and load an image
def open_image():
global path
path = filedialog.askopenfilename()
process_image('original')
# Initialize the window
root = tk.Tk()
root.title("Edge Detection GUI")
# Initialize panelA (to display the image)
panelA = None
# Initialize image path
path = None
# Create buttons for different edge detection methods
btn_open = tk.Button(root, text="Open Image", command=open_image)
btn_open.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_sobel = tk.Button(root, text="Sobel", command=lambda: process_image('sobel'))
btn_sobel.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_laplacian = tk.Button(root, text="Laplacian", command=lambda: process_image('laplacian'))
btn_laplacian.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_canny = tk.Button(root, text="Canny", command=lambda: process_image('canny'))
btn_canny.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_blur = tk.Button(root, text="Blur", command=lambda: process_image('blur'))
btn_blur.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_embossing = tk.Button(root, text="Embossing", command=lambda: process_image('embossing'))
btn_embossing.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
# Start the GUI loop
root.mainloop()
Trong đoạn mã trên:
Chúng ta khai báo hai hàm: process_image() để áp dụng các bộ lọc khác nhau lên ảnh được chọn, và open_image() để mở giao diện chọn file và tải ảnh vào.
Sử dụng Tkinter để tạo giao diện người dùng, bao gồm nút mở ảnh và nút áp dụng các bộ lọc.
Sử dụng Pillow (PIL) để hiển thị hình ảnh vì Tkinter không trực tiếp hỗ trợ hình ảnh OpenCV.
Khi người dùng chọn một bộ lọc, chương trình sẽ gọi hàm process_image() với loại bộ lọc tương ứng và hiển thị hình ảnh đã xử lý.
Đoạn mã trên tạo ra một cửa sổ Tkinter cơ bản với vài nút điều khiển để áp dụng các bộ lọc khác nhau. Bạn có thể thêm kiểu và màu sắc vào các nút và GUI bằng cách sử dụng các tùy chọn cấu hình của Tkinter, nhưng để giữ cho ví dụ ngắn gọn, tôi không bao gồm chúng ở đây.
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
# Function to process and update images
def process_image(filter_type):
global image, image_original, panelA, panelB, path
if path:
if filter_type == 'original':
processed_image = image_original.copy()
else:
# Apply the specified filter to the copy of the original image
img_gray = cv2.cvtColor(image_original, cv2.COLOR_BGR2GRAY)
if filter_type == 'sobel':
sobelX = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1)
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
processed_image = sobelCombined
elif filter_type == 'laplacian':
processed_image = cv2.Laplacian(img_gray, cv2.CV_64F)
elif filter_type == 'canny':
processed_image = cv2.Canny(img_gray, 100, 200)
elif filter_type == 'blur':
processed_image = cv2.GaussianBlur(image_original, (5, 5), 0)
elif filter_type == 'embossing':
kernel = np.array([[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]])
processed_image = cv2.filter2D(image_original, -1, kernel)
# Convert the image to PIL format and then to ImageTk format
if filter_type != 'original':
processed_image = Image.fromarray(processed_image)
else:
processed_image = Image.fromarray(cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB))
processed_image = ImageTk.PhotoImage(processed_image)
# Update the panels
if panelA is None or panelB is None:
panelA = tk.Label(image=image_original_tk)
panelA.image = image_original_tk
panelA.pack(side="left", padx=10, pady=10)
panelB = tk.Label(image=processed_image)
panelB.image = processed_image
panelB.pack(side="right", padx=10, pady=10)
else:
panelB.configure(image=processed_image)
panelB.image = processed_image
# Function to open file dialog and load an image
def open_image():
global path, image_original, image_original_tk, panelA, panelB
path = filedialog.askopenfilename()
if path:
# Load the original image
image_original = cv2.imread(path)
# Convert the image for displaying
image_display = Image.fromarray(cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB))
image_original_tk = ImageTk.PhotoImage(image_display)
# Update both panels
process_image('original')
# Initialize the window
root = tk.Tk()
root.title("Edge Detection GUI")
# Initialize panelA and panelB (to display the images)
panelA = None
panelB = None
# Initialize image path and original image
path = None
image_original = None
image_original_tk = None
# Rest of code to create the buttons and start the GUI loop remains the same
# Start the GUI loop
root.mainloop()
Trong mã này:
image_original và image_original_tk dùng để lưu và hiển thị ảnh gốc.
panelA hiển thị ảnh gốc, panelB hiển thị ảnh đã xử lý.
Cả hai panel panelA và panelB được khởi tạo chỉ một lần khi ảnh đầu tiên được mở và sau đó chỉ được cập nhật ảnh khi người dùng chọn áp dụng một bộ lọc khác.
Khi mở ảnh mới, cả hai panel đều được cập nhật để hiển thị ảnh gốc và vẫn giữ nguyên màn hình so sánh, với panelB sẽ cập nhật thành ảnh được xử lý theo yêu cầu.
Nhớ rằng kích thước panel phụ thuộc vào kích thước ảnh gốc, nên cố định kích thước panel có thể làm ảnh bị cắt hoặc co giãn không phù hợp. Để tránh điều này, bạn có thể sử dụng phương pháp resize ảnh để đảm bảo ảnh vừa với panel hoặc hiển thị ảnh với scrollbar.
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
# Function to load and process image
def process_image(filter_type):
global image, image_original, panelA, panelB, path
if path:
# Load the image and convert it to grayscale for filtering
img_gray = cv2.cvtColor(image_original, cv2.COLOR_BGR2GRAY)
# Apply the specified filter
if filter_type == 'sobel':
sobelX = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1)
processed_image = cv2.bitwise_or(sobelX, sobelY)
elif filter_type == 'laplacian':
processed_image = cv2.Laplacian(img_gray, cv2.CV_64F)
elif filter_type == 'canny':
processed_image = cv2.Canny(img_gray, 100, 200)
elif filter_type == 'blur':
processed_image = cv2.GaussianBlur(img_gray, (5, 5), 0)
elif filter_type == 'embossing':
kernel = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]])
processed_image = cv2.filter2D(img_gray, -1, kernel)
else: # Show original
processed_image = cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB)
# Convert processed image to the PIL format
processed_image_pil = Image.fromarray(np.uint8(processed_image))
# Resize the image to fit the panel
# Note: It's important to maintain aspect ratio
basewidth = 300 # Set desired width for display
wpercent = (basewidth / float(processed_image_pil.size[0]))
hsize = int((float(processed_image_pil.size[1]) * float(wpercent)))
processed_image_pil = processed_image_pil.resize((basewidth, hsize), Image.ANTIALIAS)
# Convert the PIL image to ImageTk format
processed_image_tk = ImageTk.PhotoImage(processed_image_pil)
# If the panelA is None, initialize it with original image
if panelA is None:
# Initial display of original image
original_image_pil = Image.fromarray(cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB))
# Resize the image to fit the panel
original_image_pil = original_image_pil.resize((basewidth, hsize), Image.ANTIALIAS)
# Convert the PIL image to ImageTk format
original_image_tk = ImageTk.PhotoImage(original_image_pil)
# Create the panelA and panelB
panelA = tk.Label(image=original_image_tk)
panelA.image = original_image_tk
panelA.pack(side="left", padx=10, pady=10)
panelB = tk.Label(image=processed_image_tk)
panelB.image = processed_image_tk
panelB.pack(side="right", padx=10, pady=10)
else:
# Update the panelB only with processed image
panelB.configure(image=processed_image_tk)
panelB.image = processed_image_tk
# Function to open file dialog and load an image
def open_image():
global path, image_original
path = filedialog.askopenfilename()
if path:
image_original = cv2.imread(path)
process_image('original')
# Initialize the window
root = tk.Tk()
root.title("Edge Detection GUI")
# Initialize panelA and panelB (to display the images)
panelA = None
panelB = None
# Initialize image path and original image
path = None
image_original = None
# Create an open button for loading images
btn_open = tk.Button(root, text="Open Image", command=open_image)
btn_open.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
# Create buttons for different edge detection methods
methods = ['sobel', 'laplacian', 'canny', 'blur', 'embossing']
for method in methods:
btn = tk.Button(root, text=method.title(), command=lambda m=method: process_image(m))
btn.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
# Start the GUI loop
root.mainloop()
Trong mã này:
Cửa sổ Tkinter root được khởi tạo với tiêu đề "Edge Detection GUI".
Biến panelA và panelB được sử dụng để lưu trữ 2 panel hiển thị ảnh.
Hàm open_image mở cửa sổ dialog để người dùng chọn ảnh và lưu trữ đường dẫn vào biến path.
Hàm process_image nhận đầu vào là loại bộ lọc, và dựa trên loại bộ lọc, ảnh sẽ được xử lý tương ứng.
Mỗi khi ảnh mới được mở hoặc một bộ lọc mới được áp dụng, ảnh được convert từ OpenCV sang định dạng PIL và sau đó sang ImageTk để hiển thị trong Tkinter.
Đảm bảo rằng các bức ảnh được resize để vừa với kích thước panel mong muốn, đồng thời giữ nguyên tỷ lệ khung hình.
Dùng một vòng lặp để tạo nút cho mỗi phương pháp xử lý ảnh.
Quan trọng: Kiểm tra đường dẫn đến ảnh sau khi mở một file bằng filedialog để đảm bảo rằng người dùng không chỉ đóng cửa sổ mỗi khi open_image được gọi.
Trong đoạn mã trên, chúng tôi đã tạo một hàm mới update_panels() để xử lý cập nhật của cả hai panel một cách riêng biệt, cho phép bạn cập nhật hình ảnh trên cả panelA và panelB mỗi khi bạn mở một tệp ảnh mới. Trong open_image(), chúng tôi sử dụng process_image('original') để cập nhật panelA với ảnh gốc và panelB với bản sao của ảnh gốc.
Hãy nhớ rằng bạn sẽ phải định nghĩa lại convert_image() để bao gồm mã cho các bộ lọc và chuyển đổi hình ảnh mà bạn muốn sử dụng. Hãy chắc chắn làm điều này một cách cẩn trọng để đảm bảo rằng ảnh gốc và ảnh đã xử lý đều được cập nhật đúng cách trên giao diện người dùng.
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
# Khai báo biến toàn cục
panelA = None
panelB = None
image_original = None
def process_image(filter_type):
global image_original, panelA, panelB
# Kiểm tra xem ảnh có tồn tại không
if image_original is None:
return
# Chuyển ảnh gốc về dạng grayscale
img_gray = cv2.cvtColor(image_original, cv2.COLOR_BGR2GRAY)
# Áp dụng bộ lọc theo yêu cầu
if filter_type == 'sobel':
sobelX = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1)
processed_image = cv2.bitwise_or(sobelX, sobelY)
processed_image = np.uint8(np.absolute(processed_image))
elif filter_type == 'laplacian':
processed_image = cv2.Laplacian(img_gray, cv2.CV_64F)
processed_image = np.uint8(np.absolute(processed_image))
elif filter_type == 'canny':
processed_image = cv2.Canny(img_gray, 100, 200)
elif filter_type == 'blur':
processed_image = cv2.GaussianBlur(img_gray, (5, 5), 0)
elif filter_type == 'embossing':
kernel = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]])
processed_image = cv2.filter2D(img_gray, -1, kernel)
else: # 'original' filter type
processed_image = cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB)
# Chuyển đổi ảnh đã sử lý sang định dạng để hiển thị trong Tkinter
processed_image = Image.fromarray(processed_image)
processed_image = ImageTk.PhotoImage(processed_image)
# Cập nhật panelB với ảnh xử lý
if panelB is None:
panelB = tk.Label(image=processed_image)
panelB.image = processed_image
panelB.pack(side="right", padx=10, pady=10)
else:
panelB.configure(image=processed_image)
panelB.image = processed_image
def open_image():
global image_original, panelA, path
# Mở cửa sổ dialog để chọn ảnh
path = filedialog.askopenfilename()
if len(path) > 0:
image_original = cv2.imread(path, cv2.IMREAD_COLOR)
# Chuyển đổi ảnh gốc sang định dạng Tkinter
image_original = cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB)
image_original = Image.fromarray(image_original)
image_original = ImageTk.PhotoImage(image_original)
# Cập nhật panelA với ảnh gốc
if panelA is None:
panelA = tk.Label(image=image_original)
panelA.pack(side="left", padx=10, pady=10)
panelA.configure(image=image_original)
panelA.image = image_original
# Mặc định hiển thị ảnh gốc trong panelB sau khi mở
process_image('original')
# Tạo GUI
root = tk.Tk()
root.title("Edge Detection GUI")
# Tạo nút mở ảnh
btn_open = tk.Button(root, text="Open Image", command=open_image)
btn_open.pack(side="bottom", fill="both", expand="yes", padx=10, pady="10")
# Tạo các nút cho bộ lọc
filters = [
("Sobel", "sobel"),
("Laplacian", "laplacian"),
("Canny", "canny"),
("Blur", "blur"),
("Embossing", "embossing")
]
for (text, filter_type) in filters:
btn = tk.Button(root, text=text, command=lambda f=filter_type: process_image(f))
btn.pack(side="bottom", fill="both", expand="yes", padx="10", pady="10")
root.mainloop()
Trong mã này:
Hàm open_image() chịu trách nhiệm mở một cửa sổ dialog để chọn ảnh và cập nhật panelA với ảnh gốc.
Hàm process_image() xử lý ảnh dựa trên bộ lọc được chọn và cập nhật panelB với ảnh kết quả.
Một chuỗi các nút được tạo ra cho từng loại bộ lọc, mỗi nút khi nhấn sẽ gọi hàm process_image() với loại bộ lọc tương ứng.
Chương trình sẽ hiển thị cửa sổ với nút "Open Image" để cho phép bạn chọn một ảnh. Khi ảnh được chọn, nó sẽ được hiển thị trong panelA. Ảnh sau khi áp dụng bộ lọc sẽ được hiển thị trong panelB. Bạn có thể chọn áp dụng bộ lọc khác nhau trên ảnh gốc và kết quả sẽ được cập nhật tức thì trong panelB.
Function to open file dialog and load an image
def open_image():
global path
path = filedialog.askopenfilename()
process_image('original') # Sửa dấu nháy đơn ở đây
Initialize the window
root = tk.Tk()
root.title("Edge Detection GUI")
Initialize panelA (to display the image)
panelA = None
Initialize image path
path = None
Create buttons for different edge detection methods
btn_sobel = tk.Button(root, text="Sobel", command=lambda: process_image('sobel')) # Sửa dấu nháy đơn ở đây
btn_sobel.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_laplacian = tk.Button(root, text="Laplacian", command=lambda: process_image('laplacian')) # Sửa dấu nháy đơn ở đây
btn_laplacian.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_canny = tk.Button(root, text="Canny", command=lambda: process_image('canny')) # Sửa dấu nháy đơn ở đây
btn_canny.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_blur = tk.Button(root, text="Blur", command=lambda: process_image('blur')) # Sửa dấu nháy đơn ở đây
btn_blur.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
btn_embossing = tk.Button(root, text="Embossing", command=lambda: process_image('embossing')) # Sửa dấu nháy đơn ở đây
btn_embossing.pack(side='bottom', fill="both", expand="yes", padx="10", pady="10")
Start the GUI loop
root.mainloop()
import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
# Set a fixed display size for the images
display_size = (300, 300)
# Function to load and process image
def process_image(filter_type):
global image, panelA, path
if path:
# Load the image and convert it to grayscale
image = cv2.imread(path)
# Resize the image to fit the display size
image_resized = cv2.resize(image, display_size, interpolation=cv2.INTER_AREA)
if image_resized.ndim == 3 and filter_type != 'original':
# Convert to grayscale for filtering if needed
image_resized = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)
# Apply the specified filter
if filter_type == 'sobel':
sobelX = cv2.Sobel(image_resized, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(image_resized, cv2.CV_64F, 0, 1)
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
processed_image = sobelCombined
elif filter_type == 'laplacian':
processed_image = cv2.Laplacian(image_resized, cv2.CV_64F)
elif filter_type == 'canny':
processed_image = cv2.Canny(image_resized, 100, 200)
elif filter_type == 'blur':
processed_image = cv2.GaussianBlur(image_resized, (5, 5), 0)
elif filter_type == 'embossing':
kernel = np.array([[-2, -1, 0],
[-1, 1, 1],
[0, 1, 2]])
processed_image = cv2.filter2D(image_resized, -1, kernel)
else: # 'original'
processed_image = image_resized
if processed_image.ndim == 2:
# Convert to BGR for color consistency
processed_image = cv2.cvtColor(processed_image, cv2.COLOR_GRAY2BGR)
# Convert the image to PIL format and then to ImageTk format
processed_image = Image.fromarray(processed_image)
processed_image = ImageTk.PhotoImage(processed_image)
# If the panel A is None, initialize it
if panelA is None:
panelA = tk.Label(image=processed_image)
panelA.image = processed_image
panelA.pack(side="left", padx=10, pady=10)
else: # Update the panel
panelA.configure(image=processed_image)
panelA.image = processed_image
# Function to open file dialog and load an image
def open_image():
global path
path = filedialog.askopenfilename()
if path: # If a file was selected
process_image('original')
# Initialize the window
root = tk.Tk()
root.title("Edge Detection GUI")
# Initialize panelA (to display the image)
panelA = None
# Initialize image path
path = None
# Create buttons for different edge detection methods
# ... (rest of the buttons code remains the same)
# Start the GUI loop
root.mainloop()
Các thay đổi từ bản gốc:
Thêm biến display_size để cố định kích thước ảnh hiển thị trong GUI.
Sử dụng cv2.resize() để thay đổi kích thước ảnh đầu vào trước khi áp dụng các bộ lọc, điều này đảm bảo rằng mọi ảnh đều hiển thị với kích thước nhất quán trong giao diện người dùng.
Đảm bảo rằng ảnh đầu ra luôn ở dạng BGR để tránh sự không nhất quán về màu sắc khi hiển thị.
Hãy chắc chắn kiểm tra lại đường dẫn đúng trước khi thử mở một tệp hình ảnh để tránh lỗi. Đường dẫn hình ảnh cần phải được nhập đúng định dạng và tên file.
Function to open file dialog and load an image
def open_image():
global path, image_original, panelA
code
# Open file dialog to choose an image
path = filedialog.askopenfilename()
if path:
# Load the original image
image_original = cv2.imread(path)
# Convert the image for displaying
image_display = Image.fromarray(cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB))
image_original_tk = ImageTk.PhotoImage(image_display)
# Update the panel with the original image
if panelA is None:
panelA = tk.Label(image=image_original_tk)
panelA.image = image_original_tk
panelA.pack(side="left", padx=10, pady=10)
else:
panelA.configure(image=image_original_tk)
panelA.image = image_original_tk