当前位置: 首页 > news >正文

Python面向对象,实现图片处理案例,支持:高斯模糊、Canny边缘检测、反转边缘图像、生成手绘效果、调亮度......等等

实验图片如下:
命名为img1.jpg, 放在项目下新建文件夹images下
在这里插入图片描述
项目构造如下:
在这里插入图片描述

app.py源码如下

import cv2
import os
from matplotlib import pyplot as plt
import numpy as npclass ImageProcessor:def __init__(self, image_path):self.image = cv2.imread(image_path)  # Load the imageif 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 formatself.gray_image = cv2.cvtColor(self.image, cv2.COLOR_RGB2GRAY)  # Convert to grayscaleself.blurred_image = Noneself.edges = Noneself.inverted_edges = Noneself.cartoon_image = Noneself.save_counter = 0def 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 initiallyself.save_counter += 1self.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 initiallyself.save_counter += 1self.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 initiallyself.save_counter += 1self.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 imagecolor_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 += 1self.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.")returnif 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("退出程序。")breakelse:print("无效的输入,请重新输入。")if __name__ == "__main__":main()

终端运行效果:
在这里插入图片描述
生成手绘照片处理效果如下:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

http://www.lryc.cn/news/473993.html

相关文章:

  • SOLID - 依赖倒置原则(Dependency Inversion Principle)
  • 【.NET 8 实战--孢子记账--从单体到微服务】--需求拆分与规划
  • 在macOS的多任务处理环境中,如何平衡应用的性能与用户体验?这是否是一个复杂的优化问题?如何优化用户体验|多任务处理|用户体验|应用设计
  • Vscode配置CC++编程环境的使用体验优化和补充说明
  • 十个方法杜绝CAD图纸泄密风险!2024年图纸防泄密指南!「必看」
  • 技术干货|HyperMesh CFD功能详解:虚拟风洞 Part 1
  • 022集——统计多条线的总长度(CAD—C#二次开发入门)
  • 大模型重要技术系列三:高效推理
  • Android 刘海屏适配指南
  • 微信小程序服务通知
  • Ubuntu使用Qt虚拟键盘,支持中英文切换
  • 泰州农商行
  • 扫雷(C语言)
  • 【实践功能记录8】使用UseElementSize实现表格高度自适应
  • SMO算法 公式推导
  • nodejs包管理器pnpm
  • 【postman】工具下载安装
  • Java_Springboot核心配置详解
  • 太速科技-9-基于DSP TMS320C6678+FPGA XC7V690T的6U VPX信号处理卡
  • 在线UI设计工具:创意与效率的结合
  • 【MyBatis源码】SqlSessionFactoryBuilder源码分析
  • Percona XtraBackup数据备份方案
  • 聚“芯”而行,华普微亮相第五届Silicon Labs Works With大会
  • Java 用户随机选择导入ZIP文件,解压内部word模板并入库,Windows/可视化Linux系统某麒麟国防系统...均可适配
  • 【C++】C++17结构化绑定、std::optional、std::variant、std::any
  • C#的起源。J++语言的由来?J#和J++傻傻分不清?
  • Flutter 在 对接 google play 时,利用 android studio 可视化生成 已签名的aab包
  • 使用web.dev提供的工具实现浏览器消息推送服务
  • 计算机系统结构为什么用architecture 而不是structure?
  • sqoop问题汇总记录