【Python学习】图片转素描

【Python】图片转素描,批量图片转素描

导入模块

import cv2 as cv2
import numpy as np
import os

设置源文件夹和目标文件夹

source_folder = 'D:\\python\\before'
target_folder = 'D:\\python\later'
# 确保目标文件夹存在
if not os.path.exists(target_folder):
    os.makedirs(target_folder)

遍历源文件夹中的所有文件

for filename in os.listdir(source_folder):

检查文件是否是图片(可以根据需要添加其他格式)

if filename.lower().endswith(('.png', '.jpg', '.jpeg')):

查看效果

原图:

原图

素描:

素描图片

图片处理

 image_path = os.path.join(source_folder, filename)
        image = cv2.imread(image_path)
        # 检查图片是否正确加载
        if image is None:
            print(f"Error: Unable to load image {image_path}")
            continue  # 跳过当前文件,继续处理下一个文件
        #cv2.imshow("old", image)
        #cv2.waitKey(0)
        # 转换为灰度图像
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        #cv2.imshow("gray", gray_image)
        #cv2.waitKey(0)
         
        inverted_image = 255 - gra

构造目标文件路径、保存素描到文件

        target_path = os.path.join(target_folder, 'later-' + filename)          
        cv2.imwrite(target_path, pencil_sketch)
        cv2.waitKey(0)

完整代码

import cv2 as cv2
import os

# 设置源文件夹和目标文件夹
source_folder = 'D:\\python\\before'
target_folder = 'D:\\python\later'
# 确保目标文件夹存在
if not os.path.exists(target_folder):
    os.makedirs(target_folder)

# 遍历源文件夹中的所有文件
for filename in os.listdir(source_folder):
    # 检查文件是否是图片(根据需要添加格式)
    if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        image_path = os.path.join(source_folder, filename)
        image = cv2.imread(image_path)
        # 检查图片是否正确加载
        if image is None:
            print(f"Error: 当前图片加载失败 {image_path}")
            continue  # 跳过当前文件,继续处理下一个文件
		#cv2.imshow("old", image)
        #cv2.waitKey(0)
        # 转换为灰度图像
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        #cv2.imshow("gray", gray_image)
        #cv2.waitKey(0)
        inverted_image = 255 - gray_image
        #cv2.imshow("inverted", inverted_image)
        #cv2.waitKey()
        blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
        inverted_blurred = 255 - blurred
        pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)
        #cv2.imshow("inverted_blurred", pencil_sketch)
        #cv2.waitKey(0)
         
        #cv2.imshow("original image", image)
        #cv2.imshow("pencil sketch", pencil_sketch)
        # 构造目标文件路径
        target_path = os.path.join(target_folder, 'later-' + filename)        
        # 保存素描到文件
        cv2.imwrite(target_path, pencil_sketch)

        cv2.waitKey(0)
        
print("全部图片转换完成")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值