用python给帅哥靓女们来张素描特写,图片转素描画

本工具主要是将彩色图片转换成黑白素描样式图片,给大家好玩下

源码参考了https://www.52pojie.cn/thread-1149417-1-1.html,在此基础上对中文输入路径和输出中文乱码问题进行了改进。

先上效果图(当然是我可爱的书记):

在这里插入图片描述
在这里插入图片描述

图像转换原理:图片灰度化+反色+高斯模糊+亮化混合

乱码问题解决:中文乱码,取消imread()和imwrite()方法,换用imdecode()和imencode()方法

cv2.imdecode()函数:从指定的内存缓存中读取数据,并把数据转换(解码)成图像格式;主要用于从网络传输数据中恢复出图像。
cv2.imencode()函数:是将图片格式转换(编码)成流数据,赋值到内存缓存中;主要用于图像数据格式的压缩,方便网络传输。

环境:在PyCharm中编译运行,使用Python+OpenCV模块

直接上代码:

# -*- coding:utf-8 -*-

import cv2
import numpy as np
from tkinter import filedialog, Tk
from os import getcwd
from re import findall


def open_path():
    # 图片路径
    root = Tk()
    root.withdraw()
    file_path = (filedialog.askopenfilename(title='选择图片文件', filetypes=[('All Files', '*')]))
    return file_path


def dodgeNaive(image, mask):
    # determine the shape of the input image
    width, height = image.shape[:2]

    # prepare output argument with same size as image
    blend = np.zeros((width, height), np.uint8)

    for col in range(width):
        for row in range(height):
            # do for every pixel
            if mask[col, row] == 255:
                # avoid division by zero
                blend[col, row] = 255
            else:
                # shift image pixel value by 8 bits
                # divide by the inverse of the mask
                tmp = (image[col, row] << 8) / (255 - mask)
                # print('tmp={}'.format(tmp.shape))
                # make sure resulting value stays within bounds
                if tmp.any() > 255:
                    tmp = 255
                    blend[col, row] = tmp

    return blend


def dodgeV2(image, mask):
    return cv2.divide(image, 255 - mask, scale=256)


def burnV2(image, mask):
    return 255 - cv2.divide(255 - image, 255 - mask, scale=256)


def rgb_to_sketch(src_image_name):
    print('转换中......')
    img_rgb = cv2.imdecode(np.fromfile(src_image_name, dtype=np.uint8), -1)  ##读取图片,解决中文路径问题
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    # 读取图片时直接转换操作
    # img_gray = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)

    img_gray_inv = 255 - img_gray
    img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(21, 21),
                                sigmaX=0, sigmaY=0)
    img_blend = dodgeV2(img_gray, img_blur)
    
    cv2.imencode('.jpg', img_blend)[1].tofile(dst_image_name) # 保存图像,解决输出中文乱码
    save_path = getcwd() + "\\" + dst_image_name  # 保存路径
    print('转换完成!!!\n')
    print('保存路径:' + save_path)
    cv2.imshow(save_path, img_blend)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


if __name__ == '__main__':
    print('请选择图片:')
    src_image_name = open_path()  # 文件路径
    print(src_image_name + '\n')
    image_name = ''.join(findall(r'[^\\/:*?"<>|\r\n]+$', src_image_name))  # 获取文件名
    dst_image_name = 'Sketch_' + image_name
    rgb_to_sketch(src_image_name)

嗯,就到这里了,大家如果有更好的样式改进可以在底下评论哦,嘿嘿!

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页