【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
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
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
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
inverted_image = 255 - gray_image
blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
inverted_blurred = 255 - blurred
pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)
target_path = os.path.join(target_folder, 'later-' + filename)
cv2.imwrite(target_path, pencil_sketch)
cv2.waitKey(0)
print("全部图片转换完成")