通过python将图片生成字符画

基础知识:

1.python基础知识   快速学习链接:https://www.shiyanlou.com/courses/214

2.linux命令行操作   快速学习链接:https://www.shiyanlou.com/courses/1

3.pillow库的使用     快速学习链接:http://pillow.readthedocs.io/en/latest/index.html(英文) http://www.cnblogs.com/apexchu/p/4231041.html(中文)

4.argparse库的使用 快速学习链接:http://blog.ixxoo.me/argparse.html

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

pillow库:

导入Image类:     from PIL import Image

  在python解释器下

  >>>from PIL import Image

>>>help(Image)

  查看帮助文档

  Image的文件位置 /usr/lib64/python2.7/site-packages/PIL/Image.py

使用Image类

To load an image from a file, use the open() function in the Image module:

从文件里加载图片,使用Image模块里的open()函数:

>>> from PIL import Image
>>> im = Image.open("lena.ppm")

If successful, this function returns an Image object.       如果成功,这个函数返回一个Image对象。

If the file cannot be opened, an IOError exception is raised.  如果失败,引发一个IOError.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

PIL.Image.open(fp, mode=‘r‘)

Opens and identifies the given image file.

This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new().

Parameters:
  • fp – A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.
  • mode – The mode. If given, this argument must be “r”.
Returns:
An Image object.

Raises:
IOError – If the file cannot be found, or the image cannot be opened and identified.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Image.getpixel(xy)

Returns the pixel value at a given position.

Parameters: xy – The coordinate, given as (x, y).
Returns: The pixel value. If the image is a multi-layer image, this method returns a tuple.

通过给的位置值返回像素值。

>>> from PIL import Image
>>> im = Image.open(‘cat.jpg‘)
>>> im.getpixel((1,2))
(107, 81, 22)        返回了该坐标对应的rgb像素三元祖

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Image.resize(size, resample=0)

Returns a resized copy of this image.

Parameters:
  • size – The requested size in pixels, as a 2-tuple: (width, height).
  • resample – An optional resampling filter. This can be one of PIL.Image.NEAREST, PIL.Image.BOX, PIL.Image.BILINEAR, PIL.Image.HAMMING, PIL.Image.BICUBIC or PIL.Image.LANCZOS. If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST. See: Filters.
Returns:
An Image object.

重设图片的大小,返回一个Image对象。

5种resample: PIL.Image.NEAREST, PIL.Image.BOX, PIL.Image.BILINEAR, PIL.Image.HAMMING, PIL.Image.BICUBIC or PIL.Image.LANCZOS

>>> im = Image.open(IMG)  

>>> im = im.resize((WIDTH,HEIGHT), Image.NEAREST)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

NEAREST
Pick one nearest pixel from the input image. Ignore all other input pixels.
BOX

Each pixel of source image contributes to one pixel of the destination image with identical weights. For upscaling is equivalent of NEAREST. This filter can only be used with the resize() and thumbnail() methods.

New in version 3.4.0.

BILINEAR
For resize calculate the output pixel value using linear interpolation on all pixels that may contribute to the output value. For other transformations linear interpolation over a 2x2 environment in the input image is used.
HAMMING

Produces more sharp image than BILINEAR, doesn’t have dislocations on local level like with BOX. This filter can only be used with the resize() and thumbnail() methods.

New in version 3.4.0.

BICUBIC
For resize calculate the output pixel value using cubic interpolation on all pixels that may contribute to the output value. For other transformations cubic interpolation over a 4x4 environment in the input image is used.
LANCZOS

Calculate the output pixel value using a high-quality Lanczos filter (a truncated sinc) on all pixels that may contribute to the output value. This filter can only be used with the resize() and thumbnail() methods.

New in version 1.1.3.

Filters comparison table

Filter Downscaling quality Upscaling quality Performance
NEAREST     ?????
BOX ?   ????
BILINEAR ? ? ???
HAMMING ??   ???
BICUBIC ??? ??? ??
LANCZOS ???? ???? ?

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Image.load()

Allocates storage for the image and loads the pixel data. In normal cases, you don’t need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. This method will close the file associated with the image.

Returns: An image access object.
Return type: PixelAccess Class or PIL.PyAccess

>>> im = im.load()
>>> im
<PixelAccess object at 0x7f20ebdeb990>
>>> print im[1,2]
(107, 81, 22)

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)

Returns a converted copy of this image. For the “P” mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”.

When translating a color image to black and white (mode “L”), the library uses the ITU-R 601-2 luma transform:

L = R * 299/1000 + G * 587/1000 + B * 114/1000

The default method of converting a greyscale (“L”) or “RGB” image into a bilevel (mode “1”) image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is NONE, all non-zero values are set to 255 (white). To use other thresholds, use the point() method.

Parameters:
  • mode – The requested mode. See: Modes.
  • matrix – An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.
  • dither – Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are NONE or FLOYDSTEINBERG (default).
  • palette – Palette to use when converting from mode “RGB” to “P”. Available palettes are WEB or ADAPTIVE.
  • colors – Number of colors to use for the ADAPTIVE palette. Defaults to 256.
Return type:
Image

Returns:
An Image object.

The following example converts an RGB image (linearly calibrated according to ITU-R 709, using the D65 luminant) to the CIE XYZ color space:

rgb2xyz = (
    0.412453, 0.357580, 0.180423, 0,
    0.212671, 0.715160, 0.072169, 0,
    0.019334, 0.119193, 0.950227, 0 )
out = im.convert("RGB", rgb2xyz)

-------------------------------------------------------------------------------------------------------------------------------------------

时间: 2024-10-06 07:06:55

通过python将图片生成字符画的相关文章

python如何根据图片生成字符画 实例教程

教大家如何用python生成字符画,看起来很炫酷. 思路:原图->灰度->根据像素亮度-映射到指定的字符序列中->输出.字符越多,字符变化稠密.效果会更好.如果根据灰度图的像素亮度范围制作字符画,效果会更好.如果再使用调色板,对字符进行改色,就更像原图了.代码: import Image chars =" ...',;:clodxkLO0DGEKNWMM" fn=r'c:\users\liabc\desktop\jianbing.png' f1=lambda F:''

Python关于图片转换为字符画的实验

对原来的实验要求的原代码做出了一下的两点改进:1.手动输入字符串的高和宽 2.生成的新的txt文件自定义文件名,原来的代码中由于指定文件名,导致当使用新图片时原先图片生成的txt文件会被覆盖. 对原先的代码做了详细的注释, 关于rgb:x/len(ascii_char)=gray/alpha+1 原文地址:https://www.cnblogs.com/lth1005/p/8870532.html

python学习---50行代码实现图片转字符画1

转自:https://blog.csdn.net/mm1030533738/article/details/78447714 项目链接: https://www.shiyanlou.com/courses/370/labs/1191/document from PIL import Image #从PIL模块中引入Image这个类import argparse  #引入argparse这个模块(argparse库是用来管理命令行参数输入的) parser = argparse.ArgumentP

python 图片转字符画

整代码: 将以下代码保存为py文件 from PIL import Image import argparse #命令行输入参数处理 parser = argparse.ArgumentParser() parser.add_argument('file') #输入文件 parser.add_argument('-o', '--output') #输出文件 parser.add_argument('--width', type = int, default = 80) #输出字符画宽 parse

Python图片转字符画

目的:将一张图片转换成字符画,采用灰度值与字符对应的算法实现像素与字符之间的转化,另外通过 argparse实现命令行参数管理,argparse其作用是为文件添加命令行参数并获取,用于程序运行输入 关键算法: # 将256灰度映射到70个字符上def get_char(r, b, g, alpha=256): if alpha == 0: return ' ' length = len(ascii_char) gray = int(0.2126 * r + 0.7152 * g + 0.0722

Python3:图片转字符画

防伪码:没有相当程度的孤独是不可能有内心的平和. 1.环境准备 主机名 IP 系统 Python版本 Python-01 192.168.10.9 CentOS release 6.9 (Final) 3.5.4 参考:https://www.shiyanlou.com/courses/370/labs/1191/document 2.原理 字符画是一系列字符的组合,可以把字符看作是比较大块的像素,一个字符能表现一种颜色(暂且这么理解吧),字符的种类越多,可以表现的颜色也越多,图片也会更有层次感

python3实现图片转字符画

用练习学习python3. #!/usr/bin/env python3 #-*- coding:utf-8 -*- from PIL import Image import argparse ''' argparse模块使得编写用户友好的命令行接口非常容易.程序只需定义好它要求的参数,然后argparse将负责如何从sys.argv中解析出这些参数.argparse模块还会自动生成帮助和使用信息并且当用户赋给程序非法的参数时产生错误信息. 使用步骤: 1.导入模块 import argpars

Swift 实现图片转字符画的功能

本文介绍一个IOS APP , 将图片转换成ASCII字符画,使用Swift语言编写. 举个例子,我们使用著名的蕾娜照片作为原图片 经APP转换后形成的字符画,我们打印出来,效果如下: 放大她的脸部可以看到图像都是字符串组成的! 项目地址: https://github.com/ijoshsmith/swift-ascii-art 字符画原理 图像中的每个像素都对应到一个ASCII值,在这里显示为一个字符. 图像中的每个像素都会被转换成一个中间值,如下所示: 让我们一步步来分析. 首先,我们将一

图片处理拓展篇 : 图片转字符画(ascii)

首先要明确思路, 图片是由像素组成的, 不同的像素有不同的颜色(rgb), 那么既然我们要转化为字符画, 最直接的办法就是利用字符串来替代像素, 也就是用不同的字符串来代表不同的像素. 另外图片一般来讲是彩色的, 而acsii(一般打印在终端上吧) 都是黑白的, 此时就要介绍另外一个概念了 : 灰度值:指黑白图像中点的颜色深度,范围一般从0到255,白色为255,黑色为0,故黑白图片也称灰度图像. 到这里思路就很明确了, 我们要做的就是两件事 : 1. 将每一个像素点(彩色图片用rgb)映射到每