python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python 图片色彩转换

Python 实现图片色彩转换案例

作者:剑客阿良_ALiang

我们在看动漫、影视作品中,当人物在回忆过程中,体现出来的画面一般都是黑白或者褐色的。本文将提供将图片色彩转为黑白或者褐色风格的案例详解,感兴趣的小伙伴可以了解一下。

前言

本文提供将图片色彩转为黑白或者褐色风格。比较类似于我们在看动漫、影视作品中,当人物在回忆过程中,体现出来的画面一般都是黑白或者褐色的。

环境依赖

ffmpeg环境依赖,ffmpy依赖安装

pip install ffmpy -i https://pypi.douban.com/simple

代码

不废话,上代码

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author  : 剑客阿良_ALiang
@file   : image_change_color_tool.py
@ide    : PyCharm
@time   : 2021-11-19 15:10:22
"""
import os
import uuid
from ffmpy import FFmpeg
 
 
# 黑白图
def black_and_white(image_path: str, output_dir: str):
    ext = _check_format(image_path)
    result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
    ff = FFmpeg(inputs={image_path: None},
                outputs={result: '-vf colorchannelmixer=.3:.4:.3:0:.3:.4:.3:0:.3:.4:.3 -y'})
    print(ff.cmd)
    ff.run()
    return result
 
 
# 褐色
def brown(image_path: str, output_dir: str):
    ext = _check_format(image_path)
    result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
    ff = FFmpeg(inputs={image_path: None},
                outputs={result: '-vf colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131 -y'})
    print(ff.cmd)
    ff.run()
    return result
 
 
def _check_format(image_path: str):
    ext = os.path.basename(image_path).strip().split('.')[-1]
    if ext not in ['png', 'jpg']:
        raise Exception('format error')
    return ext

代码说明

1、两个方法入参均为:图片路径、输出目录路径。

2、为了避免文件名重复,使用uuid作为文件名。

3、图片的后缀格式判断只有两种,如需增加,自行添加即可。

验证一下

图片准备,原图如下:

验证代码

if __name__ == '__main__':
    print(black_and_white('C:/Users/huyi/Desktop/4.jpg', 'C:/Users/huyi/Desktop/'))
    print(brown('C:/Users/huyi/Desktop/4.jpg', 'C:/Users/huyi/Desktop/'))

执行结果

PyDev console: starting.
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
runfile('D:/spyder/csdn/image_change_color_tool.py', wdir='D:/spyder/csdn')
ffmpeg -i C:/Users/huyi/Desktop/4.jpg -vf colorchannelmixer=.3:.4:.3:0:.3:.4:.3:0:.3:.4:.3 -y C:/Users/huyi/Desktop/c7052ed8-d5db-4e84-9c01-88d661c967a5.jpg
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, image2, from 'C:/Users/huyi/Desktop/4.jpg':
  Duration: 00:00:00.04, start: 0.000000, bitrate: 101138 kb/s
    Stream #0:0: Video: mjpeg (Progressive), yuvj444p(pc, bt470bg/unknown/unknown), 1920x1080, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
Press [q] to stop, [?] for help
[swscaler @ 000001625402e2c0] deprecated pixel format used, make sure you did set range correctly
[swscaler @ 0000016253b14f80] deprecated pixel format used, make sure you did set range correctly
Output #0, image2, to 'C:/Users/huyi/Desktop/c7052ed8-d5db-4e84-9c01-88d661c967a5.jpg':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0: Video: mjpeg, yuvj444p(pc), 1920x1080, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.91.100 mjpeg
    Side data:
      cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A
frame=    1 fps=0.0 q=9.2 Lsize=N/A time=00:00:00.04 bitrate=N/A speed=0.232x    
video:133kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
C:/Users/huyi/Desktop/c7052ed8-d5db-4e84-9c01-88d661c967a5.jpg
ffmpeg -i C:/Users/huyi/Desktop/4.jpg -vf colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131 -y C:/Users/huyi/Desktop/9282f36a-2361-4b0d-a115-56864c9d2337.jpg
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, image2, from 'C:/Users/huyi/Desktop/4.jpg':
  Duration: 00:00:00.04, start: 0.000000, bitrate: 101138 kb/s
    Stream #0:0: Video: mjpeg (Progressive), yuvj444p(pc, bt470bg/unknown/unknown), 1920x1080, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
Press [q] to stop, [?] for help
[swscaler @ 0000013b05762f80] deprecated pixel format used, make sure you did set range correctly
[swscaler @ 0000013b052c4fc0] deprecated pixel format used, make sure you did set range correctly
Output #0, image2, to 'C:/Users/huyi/Desktop/9282f36a-2361-4b0d-a115-56864c9d2337.jpg':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0: Video: mjpeg, yuvj444p(pc), 1920x1080, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.91.100 mjpeg
    Side data:
      cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A
frame=    1 fps=0.0 q=9.5 Lsize=N/A time=00:00:00.04 bitrate=N/A speed=0.129x    
video:177kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
C:/Users/huyi/Desktop/9282f36a-2361-4b0d-a115-56864c9d2337.jpg

黑白图效果

褐色图效果

到此这篇关于Python 实现图片色彩转换案例的文章就介绍到这了,更多相关Python 图片色彩转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文