实验图片如下:
命名为img1.jpg, 放在项目下新建文件夹images下
项目构造如下:
app.py源码如下
import cv2
import os
from matplotlib import pyplot as plt
import numpy as np
class ImageProcessor:
def __init__(self, image_path):
self.image = cv2.imread(image_path) # Load the image
if self.image is None:
raise ValueError("Image not found or unable to load.")
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB) # Convert to RGB format
self.gray_image = cv2.cvtColor(self.image, cv2.COLOR_RGB2GRAY) # Convert to grayscale
self.blurred_image = None
self.edges = None
self.inverted_edges = None
self.cartoon_image = None
self.save_counter = 0
def apply_gaussian_blur(self, ksize=(5, 5), sigmaX=0):
self.blurred_image = cv2.GaussianBlur(self.gray_image, ksize, sigmaX)
self.cartoon_image = self.blurred_image # Assuming cartoon_image should be blurred initially
self.save_counter += 1
self.save_image(f'new{self.save_counter}.jpg')
def detect_edges(self, threshold1=50, threshold2=150):
self.apply_gaussian_blur()
self.edges = cv2.Canny(self.blurred_image, threshold1, threshold2)
self.cartoon_image = self.edges # Assuming cartoon_image should show edges initially
self.save_counter += 1
self.save_image(f'new{self.save_counter}.jpg')
def invert_edges(self):
self.detect_edges()
self.inverted_edges = cv2.bitwise_not(self.edges)
self.cartoon_image = self.inverted_edges # Assuming cartoon_image should show inverted edges initially
self.save_counter += 1
self.save_image(f'new{self.save_counter}.jpg')
def create_cartoon_effect(self):
self.invert_edges()
# Create a cartoon effect by combining edges and original image
color_image = cv2.bilateralFilter(self.image, d=9, sigmaColor=75, sigmaSpace=75)
self.cartoon_image = cv2.bitwise_and(color_image, color_image, mask=self.inverted_edges)
self.save_counter += 1
self.save_image(f'new{self.save_counter}.jpg')
def save_image(self, filename):
if self.cartoon_image is None or self.cartoon_image.size == 0:
print("Cartoon image is empty, skipping save.")
return
if not os.path.exists('../newImg'):
os.makedirs('../newImg')
cv2.imwrite(f'newImg/{filename}', cv2.cvtColor(self.cartoon_image, cv2.COLOR_RGB2BGR))
print(f"图片已保存为 newImg/{filename}")
def show_images(self):
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus'] = False # 解决坐标轴负号显示问题
plt.figure(figsize=(10, 10))
plt.subplot(1, 2, 1)
plt.title("原图片")
plt.imshow(self.image)
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title("处理后的图片")
plt.imshow(self.cartoon_image)
plt.axis('off')
plt.show()
def main():
image_path = '../images/img1.jpg' # 请确保路径正确
processor = ImageProcessor(image_path)
while True:
print("\n请选择图片处理功能编号:")
print("1 - 高斯模糊")
print("2 - Canny边缘检测")
print("3 - 反转边缘图像")
print("4 - 生成手绘效果")
print("5 - 显示图片")
print("0 - 退出")
choice = input("输入你的选择:")
if choice == '1':
processor.apply_gaussian_blur()
print("高斯模糊已应用并保存。")
elif choice == '2':
processor.detect_edges()
print("Canny边缘检测已应用并保存。")
elif choice == '3':
processor.invert_edges()
print("边缘图像已反转并保存。")
elif choice == '4':
processor.create_cartoon_effect()
print("手绘效果已生成并保存。")
elif choice == '5':
processor.show_images()
elif choice == '0':
print("退出程序。")
break
else:
print("无效的输入,请重新输入。")
if __name__ == "__main__":
main()
终端运行效果:
生成手绘照片处理效果如下: