typeAliases Eclipse插件 iic 自动化部署 object dll testng mysql操作日志 erp项目描述 map删除指定元素 python正则匹配中文 普通话网上报名 python基础练习 java的环境配置 javahttp java配置文件 linux内核编程 linux命令详解词典 网络电视软件下载 端口关闭工具 dvwa安装教程 js延迟加载的方式 pr转场特效下载 qq免安装版 dep wscript adobe卸载工具 hyqihei pr时间轴 fastcgi autocad2004迷你版 驱动程序更新 汇通启富下载 骰子牛牛 python字符串 拼多多推广软件 eclipse汉化版 仁王木灵全收集 gmail邮箱打不开 winloader
当前位置: 首页 > 学习教程  > 编程语言

Python: PIL基本代码

2020/12/5 9:53:39 文章标签:

Python: PIL基本代码 # 声明使用字符库 # -*- coding: utf-8 -*- # 导入系统库 import os # 导入文件读写库 import io # 导入数学库 import math # 导入 PIL 图像库(The Image Module) from PIL import Image # 导入 PIL 图像通道运算库(Th…

Python: PIL基本代码

# 声明使用字符库
# -*- coding: utf-8 -*-
# 导入系统库
import os
# 导入文件读写库
import io
# 导入数学库
import math
# 导入 PIL 图像库(The Image Module)
from PIL import Image
# 导入 PIL 图像通道运算库(The ImageChops Module)
from PIL import ImageChops
# 导入 PIL 图像绘制库(The ImageDraw Module)
from PIL import ImageDraw
# 导入 PIL 图像增强库(The ImageEnhance Module)
from PIL import ImageEnhance
# 导入 PIL 图像滤波库(The ImageFilter Module)
from PIL import ImageFilter
# 导入 PIL 图像截屏库(The ImageGrab Module)
from PIL import ImageGrab
# 导入 PIL 图像运算库(The ImageOps Module)
from PIL import ImageOps
# 导入 PIL 图像统计库(The ImageStat Module)
from PIL import ImageStat
# 导入 PIL 图像字符库
from PIL import ImageFont
# 导入 Matplotlib 库
from pylab import *
# 导入 NumPy 库
from numpy import *
# 保持命名空间
# 导入 NumPy 库
import numpy as np
# 导入 Matplotlib 库
import matplotlib.pyplot as plt

# 显示数据
print("PI=%10.3f;" % math.pi)
print("PI=%06d;" % int(math.pi))

# 直接读取Color图像
PilImg_Color = Image.open('empire.jpg')
# PilImg_Color.show()
print("格式:", PilImg_Color.format, "    大小:", PilImg_Color.size,
      "    模式:", PilImg_Color.mode)

# 根据字符串名称读取Color图像
NameString = io.StringIO()
NameString.write('empire.jpg')
print(NameString.getvalue())
PilImg_String = Image.open(NameString.getvalue())
# PilImg_String.show()

# 将Color图像转换为Bin图像
PilImg_Bin = PilImg_Color.convert('1')
# PilImg_Bin.show()

# 将Color图像转换为Gray图像
PilImg_Gray = PilImg_Color.convert('L')
# PilImg_Gray.show()

# 将Color图像转换为Color Palette图像
PilImg_Palette = PilImg_Color.convert('P')
# PilImg_Palette.show()

# 将Color图像转换为RGB图像
PilImg_RGB = PilImg_Color.convert('RGB')
# PilImg_RGB.show()

# 将Color图像转换为RGBA图像
PilImg_RGBA = PilImg_Color.convert('RGBA')
# PilImg_RGBA.show()

# 将Color图像转换为CMYK图像
PilImg_CMYK = PilImg_Color.convert('CMYK')
# PilImg_CMYK.show()

# 将Color图像转换为YCbCr图像
PilImg_YCbCr = PilImg_Color.convert('YCbCr')
# PilImg_YCbCr.show()

# 将Color图像转换为I图像
PilImg_I = PilImg_Color.convert('I')
# PilImg_I.show()

# 将Color图像转换为F图像
PilImg_F = PilImg_Color.convert('F')
# PilImg_F.show()

'''
# 从文件名列表(filelist)中读取所有的图像文件,并转换成JPEG格式
from PIL import Image
import os
for infile in filelist:
outfile = os.path.splitext(infile)[0] + ".jpg"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
print "cannot convert", infile
'''

'''
# 创建一个包含文件夹中所有图像文件的文件名列表。
# 首先新建一个文件,命名为 imtools.py,来存储一些经常使用的图像操作,
# 然后将下面的函数添加进去
import os
def get_imlist(path):
""" 返回目录中所有 JPG 图像的文件名列表 """
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
'''

"""
The Image Module
"""
# 创建新图像(new)
# 1.Image.new(mode, size) ⇒ image
# 2.Image.new(mode, size, color) ⇒ image
Mode_NewImg = "RGB"
Width_NewImg = 800
Height_NewImg = 640
Color_NewImg = "#78b8e7"
PilImg_Color_New = Image.new(Mode_NewImg, (Width_NewImg, Height_NewImg),
                             Color_NewImg)
# PilImg_Color_New.show()

# 融合图像(blend)
# Image.blend(image1, image2, alpha) ⇒ image
PilImg_Blend1 = Image.open('融合1.jpg')
PilImg_Blend2 = Image.open('融合2.jpg')
BlendAlpha = 0.20
PilImg_Blend = Image.blend(PilImg_Blend1, PilImg_Blend2, BlendAlpha)
# PilImg_Blend.show()

# 复合图像(composite)
# Image.composite(image1, image2, mask) ⇒ image
PilImg_Composite = Image.open('融合1.jpg')
PilImg_Composite1 = PilImg_Composite.convert('RGB')
PilImg_Composite = Image.open('融合2.jpg')
PilImg_Composite2 = PilImg_Composite.convert('RGB')
PilImg_Composite = PilImg_Color_New.copy()
PilImg_Composite3 = PilImg_Composite.convert('1')  # "1"、"L"、"RGBA"
PilImg_Composite = Image.composite(PilImg_Composite1,
                                   PilImg_Composite2, PilImg_Composite3)
# PilImg_Composite.show()

# eval
# Image.eval(image, function) ⇒ image

# frombuffer
# Image.frombuffer(mode, size, data) ⇒ image
# 仅支持“L”, “RGBX”, “RGBA”, and “CMYK”
# im = Image.frombuffer(mode, size, data, "raw", mode, 0, 1)

# fromstring
# Image.fromstring(mode, size, data) ⇒ image

# 合并图像(merge)
# Image.merge(mode, bands) ⇒ image
# PilImg_Merge1 = Image.open('融合1.jpg')
# PilImg_Merge2 = Image.open('融合2.jpg')
# PilImg_Merge = Image.blend(PilImg_Merge1, PilImg_Merge2)
# PilImg_Merge.show()

# 转换图像(convert)
# im.convert(mode) ⇒ image
PilImg_Convert1 = Image.open('图像4.jpg')
# PilImg_Convert1 = PilImg_Convert1.convert("RGBA")   # "1"\"L"\"RGB"\"RGBA"
# PilImg_Convert1.show()
# dither = "FLOYDSTEINBERG"
PilImg_Convert2 = PilImg_Convert1.convert("P", dither=Image.FLOYDSTEINBERG,
                                          palette=Image.WEB, colors=5)
# PilImg_Convert2.show()

rgb2xyz = (
    0.412453, 0.357580, 0.180423, 0,
    0.212671, 0.715160, 0.072169, 0,
    0.019334, 0.119193, 0.950227, 0)
PilImg_Convert3 = PilImg_Convert1.convert("RGB", rgb2xyz)
# PilImg_Convert3.show()

# 复制图像(copy)
PilImg_Color_Copy = PilImg_Color.copy()
PilImg_Gray_Copy = PilImg_Gray.copy()

# 裁切图像(crop)
Region = (100, 100, 400, 400)
PilImg_Crop = PilImg_Color.crop(Region)
# PilImg_Crop.show()

# 草稿(draft)
# im.draft(mode, size)
PilImg_Draft = Image.open('图像4.jpg')
PilImg_Draft.draft(mode='L', size=(120, 100))  # "L"\"RGB"\"RGBA"
# PilImg_Draft.show()

# 图像滤波(filter)
# im.filter(filter) ⇒ image
PilImg_Filter1 = Image.open('图像4.jpg')
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.BLUR)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.CONTOUR)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.DETAIL)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.EDGE_ENHANCE)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.EDGE_ENHANCE_MORE)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.EMBOSS)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.FIND_EDGES)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.GaussianBlur)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.MaxFilter(3))
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.MedianFilter(15))
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.MinFilter(3))
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.ModeFilter(5))
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.RankFilter)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.SHARPEN)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.SMOOTH)
# PilImg_Filter = PilImg_Filter1.filter(ImageFilter.SMOOTH_MORE)
PilImg_Filter = PilImg_Filter1.filter(ImageFilter.UnsharpMask)
# PilImg_Filter.show()

# 获得通道名称(getbands)
# im.getbands() ⇒ tuple of strings
PilImg_Getbands1 = Image.open('图像4.jpg')
PilImg_Getbands2 = PilImg_Getbands1.convert('RGBA')
PilImg_Getbands = PilImg_Getbands2.getbands()
print("通道名称:", PilImg_Getbands)

# 获得图像大小(getbbox)
# im.getbbox() ⇒ 4-tuple or None
PilImg_Getbbox1 = Image.open('图像4.jpg')
PilImg_Getbbox = PilImg_Getbbox1.getbbox()
print("图像大小:", PilImg_Getbbox)

# 获得一个未排序列表,其元素是元组(count, color)(getcolors)
# im.getcolors() ⇒ a list of (count, color) tuples or None
# im.getcolors(maxcolors) ⇒ a list of (count, color) tuples or None
PilImg_Getcolors1 = Image.open('图像4.jpg')
PilImg_Getcolors = PilImg_Getcolors1.getcolors()
# print("图像颜色:", PilImg_Getcolors.color)

# 以序列方式返回图像内容(getdata)
# im.getdata() ⇒ sequence
Image_Size = (6, 6)
PilImg_Getdata1 = Image.open('图像4.jpg')
PilImg_Getdata2 = PilImg_Getdata1.resize(Image_Size)
PilImg_Getdata = PilImg_Getdata2.getdata()
print("图像数据:", list(PilImg_Getdata))

# 获得图像最小值和最大值的二元数组(getextrema)
# im.getextrema() ⇒ 2-tuple
PilImg_Getextrema1 = Image.open('图像4.jpg').convert('L')
PilImg_Getextrema = PilImg_Getextrema1.getextrema()
print("图像最小值和最大值:", PilImg_Getextrema)

# 返回给定位置的像素值(getpixel)
# im.getpixel(xy) ⇒ value or tuple
PilImg_Getpixel1 = Image.open('图像4.jpg')
PilImg_Getpixel = PilImg_Getpixel1.getpixel((150, 150))
print("像素值:", PilImg_Getpixel)

# 计算图像直方图(histogram)
# im.histogram() ⇒ list
PilImg_Histogram1 = Image.open('图像4.jpg').convert('L')
PilImg_Histogram = PilImg_Histogram1.histogram()
print("图像直方图:", list(PilImg_Histogram))

# 为图像分配内存并从文件中加载(load)
# pix = Image.load('图像4.jpg')
# print(pix[100, 100])
# pix[100, 100] = (100, 200, 150)

# 将图像粘贴到另一张图像上(paste)
# im.paste(image, box)
PilImg_Paste1 = Image.open('图像6.jpg')
PilImg_Paste = Image.open('图像1.jpg')
PilImg_Paste.paste(PilImg_Paste1, (100, 100))
Region = (600, 600, 1112, 1112)
PilImg_Paste2 = PilImg_Paste1.resize((1112 - 600, 1112 - 600))
PilImg_Paste.paste(PilImg_Paste2, Region)
# PilImg_Paste.show()

# 根据查找表进行映射每个像素,然后返回一个图像的副本(point)
# im.point(table) ⇒ image
# im.point(function) ⇒ image
# im.point(table, mode) ⇒ image
# im.point(function, mode) ⇒ image

# 拷贝给定通道图像到当前图像的alpha层(putalpha)
# im.putalpha(band)
PilImg_Putalpha1 = Image.open('图像4.jpg').convert('L')
PilImg_Putalpha = Image.open('图像5.jpg')
PilImg_Putalpha.putalpha(PilImg_Putalpha1)
# PilImg_Putalpha.show()

# 从序列对象拷贝像素值到图像(putdata)
# im.putdata(data)
# im.putdata(data, scale, offset)

# 把一个调色板附加到"P"或"L"模式的图像(putpalette)
# im.putpalette(sequence)

# 将“L”或“RGB”图像转换成带有给定颜色的“P”图像,并返回新图像(quantize)
# im.quantize(colors, **options) ⇒ image
PilImg_Quantize1 = Image.open('图像5.jpg')
PilImg_Quantize = PilImg_Quantize1.convert("P", palette=Image.ADAPTIVE,
                                           colors=256)
# PilImg_Quantize.show()

# 调整图像大小(resize)
# im.resize(size) ⇒ image
# im.resize(size, filter) ⇒ image
PilImg_Resize1 = Image.open('图像5.jpg')
PilImg_Resize1 = PilImg_Resize1.resize((256, 256))
# filter="NEAREST"\"BILINEAR"\"BICUBIC"\"ANTIALIAS"
PilImg_Resize2 = PilImg_Resize1.resize((256, 256), Image.NEAREST)
# PilImg_Resize2.show()

# 按给定的角度顺时针旋转图像(rotate)
# im.rotate(angle) ⇒ image
# im.rotate(angle, filter=NEAREST, expand=0) ⇒ image
PilImg_Rotate1 = Image.open('图像5.jpg')
PilImg_Rotate2 = PilImg_Rotate1.rotate(30)
# filter="NEAREST"\"BILINEAR"\"BICUBIC"
PilImg_Rotate3 = PilImg_Rotate1.rotate(30, Image.BICUBIC, 1)
# PilImg_Rotate3.show()

# 保存图像(save)
# im.save(outfile, options…)
# im.save(outfile, format, options…)

# 在一个序列文件中寻找指定的帧,seek超过了序列结尾时产生EOFError异常。
# im.seek(frame)

# 显示一幅图像(show)
# im.show()

# 分离图像(split)
PilImg_Split = Image.open('图像6.jpg')
R, G, B = PilImg_Split.split()
# B.show()
PilImg_Merge = Image.merge("RGB", (B, G, R))
# PilImg_Merge.show()

# 获得当前帧数(tell)
# im.tell() ⇒ integer

# 创建缩略图
# im.thumbnail(size)
# im.thumbnail(size, filter)
# filter="NEAREST"\"BILINEAR"\"BICUBIC"\"ANTIALIAS"
PilImg_Thumbnail = Image.open('图像6.jpg')
PilImg_Thumbnail.thumbnail((512, 512))
PilImg_Thumbnail.thumbnail((256, 256), Image.ANTIALIAS)
# PilImg_Thumbnail.show()

# 返回被转换成X11位图的图像()
# im.tobitmap() ⇒ bitmap
PilImg_Tobitmapl = Image.open('图像6.bmp').resize((32, 32)).convert('1')
PilImg_Tobitmap = PilImg_Tobitmapl.tobitmap()
print(PilImg_Tobitmap)

# 使用标准的“原始”编码器返回一个包含像素数据的字符串(tobytes)
# im.tobytes() ⇒ string
# im.tobytes(encoder, parameters) ⇒ string
PilImg_Tobytes1 = Image.open('图像6.bmp').resize((32, 32)).convert('1')
PilImg_Tobytes = PilImg_Tobytes1.tobytes()
print(PilImg_Tobytes)

# 变换图像
# im.transform(size, method, data) ⇒ image
# im.transform(size, method, data, filter) ⇒ image
# filter="NEAREST"\"BILINEAR"\"BICUBIC"
PilImg_Transform1 = Image.open('图像6.jpg')
# im.transform(size, EXTENT, data) ⇒ image
# im.transform(size, EXTENT, data, filter) ⇒ image
PilImg_Transform1 = PilImg_Transform1.transform(
    (512, 512), Image.EXTENT, (100, 100, 800, 800), Image.BICUBIC)
# im.transform(size, AFFINE, data) ⇒ image
# im.transform(size, AFFINE, data, filter) ⇒ image
# (a x + b y + c, d x + e y + f)
PilImg_Transform2 = PilImg_Transform1.transform(
    (512, 512), Image.AFFINE,
    (0.15, 0.25, 25, 0.10, 0.20, 30), Image.BICUBIC)
# im.transform(size, QUAD, data) ⇒ image
# im.transform(size, QUAD, data, filter) ⇒ image
# (x0, y0, x1, y1, x2, y2, y3, y3)
PilImg_Transform3 = PilImg_Transform1.transform(
    (512, 512), Image.QUAD,
    (10, 10, 640, 10, 700, 800, 800, 800), Image.BICUBIC)
# im.transform(size, MESH, data) image ⇒ image
# im.transform(size, MESH, data, filter) image ⇒ image
# PilImg_Transform = PilImg_Transform1.convert('F').transform(
#        (512, 512), Image.MESH,
#        (10, 10, 640, 10, 700, 800, 800, 800), Image.BICUBIC)
# im.transform(size, PERSPECTIVE, data) image ⇒ image
# im.transform(size, PERSPECTIVE, data, filter) image ⇒ image
PilImg_Transform4 = PilImg_Transform1.transform(
    (512, 512), Image.PERSPECTIVE,
    (0.05, 0.05, 200, 0.10, 0.05, 400, 0.05, 0.05),
    Image.BICUBIC)
# PilImg_Transform4.show()

# 转置图像(transpose)
# im.transpose(method) ⇒ image
PilImg_Transpose1 = Image.open('图像6.jpg')
# "FLIP_LEFT_RIGHT"\"FLIP_TOP_BOTTOM"\"ROTATE_90"\"ROTATE_180"\"ROTATE_270"
PilImg_Transpose = PilImg_Transpose1.transpose(Image.ROTATE_270)
# PilImg_Transpose.show()

# 试图确定该文件是否被破坏,而不需要实际解码图像数据(verify)
# im.verify()
PilImg_Transpose1 = Image.open('图像6.jpg')
PilImg_Transpose1.verify()

# 获得图像属性
PilImg_Attributes = Image.open('图像6.jpg')
print("****图像属性****")
print("图像格式:", PilImg_Attributes.format)
print("图像模式:", PilImg_Attributes.mode)
print("图像大小:", PilImg_Attributes.size)
print("图像调色板:", PilImg_Attributes.palette)
# print("图像信息:", PilImg_Attributes.info)

# 生成指定灰度值图像(constant)
# ImageChops.constant(image, value) ⇒ image
PilImg_Constant1 = Image.open('图像6.jpg')
PilImg_Constant = ImageChops.constant(PilImg_Constant1, 128)
# PilImg_Constant.show()

# 复制图像(duplicate)
# ImageChops.duplicate(image) ⇒ image
PilImg_Duplicate1 = Image.open('图像6.jpg')
PilImg_Duplicate = ImageChops.duplicate(PilImg_Duplicate1)
# PilImg_Duplicate.show()

# 反转图像(invert)。公式:out = MAX - image。
# ImageChops.invert(image) ⇒ image
PilImg_Invert1 = Image.open('图像6.jpg')
PilImg_Invert = ImageChops.invert(PilImg_Invert1)
# PilImg_Invert.show()

# 按像素比较图像(lighter)。公式:out = max(image1, image2)。
# ImageChops.lighter(image1, image2) ⇒ image
PilImg_Lighter1 = Image.open('图像5.jpg')
PilImg_Lighter2 = Image.open('图像6.jpg')
PilImg_Lighter = ImageChops.lighter(PilImg_Lighter1, PilImg_Lighter2)
# PilImg_Lighter.show()

# 按像素比较图像(darker)。公式:out = min(image1, image2)。
# ImageChops.darker(image1, image2) ⇒ image
PilImg_Darker1 = Image.open('图像5.jpg')
PilImg_Darker2 = Image.open('图像6.jpg')
PilImg_Darker = ImageChops.darker(PilImg_Darker1, PilImg_Darker2)
# PilImg_Darker.show()

# 计算图像差值的绝对值(difference)。公式:out = abs(image1 - image2)。
# ImageChops.difference(image1, image2) ⇒ image
PilImg_Difference1 = Image.open('图像5.jpg')
PilImg_Difference2 = Image.open('图像6.jpg')
PilImg_Difference = ImageChops.difference(PilImg_Difference1,
                                          PilImg_Difference2)
# PilImg_Difference.show()

# 图像相乘(multiply)。公式:out = image1 * image2 / MAX。
# 如果你把一个图像和一个实心的黑色图像相乘,结果是黑色的。如果你用一个纯白色的图像,图像是不受影响的。
# ImageChops.multiply(image1, image2) ⇒ image
PilImg_Multiply1 = Image.open('图像5.jpg')
PilImg_Multiply2 = Image.open('图像6.jpg')
PilImg_Multiply = ImageChops.multiply(PilImg_Multiply1, PilImg_Multiply2)
# PilImg_Multiply.show()

# 反转图像乘法(screen)。公式:out = MAX - ((MAX - image1) * (MAX - image2) / MAX)。
# ImageChops.screen(image1, image2) ⇒ image
PilImg_Screen1 = Image.open('图像5.jpg')
PilImg_Screen2 = Image.open('图像6.jpg')
PilImg_Screen = ImageChops.screen(PilImg_Screen1, PilImg_Screen2)
# PilImg_Screen.show()

# 图像加法运算,并根据比例调整运算结果(add)。公式:out = (image1 + image2) / scale + offset。
# ImageChops.add(image1, image2, scale, offset) ⇒ image
PilImg_Add1 = Image.open('图像5.jpg')
PilImg_Add2 = Image.open('图像6.jpg')
PilImg_Add = ImageChops.add(PilImg_Add1, PilImg_Add2, 2.0, 30)
# PilImg_Add.show()

# 图像减法运算,并根据比例调整运算结果(subtract)。公式:out = (image1 - image2) / scale + offset。
# ImageChops.subtract(image1, image2, scale, offset) ⇒ image
PilImg_Subtract1 = Image.open('图像5.jpg')
PilImg_Subtract2 = Image.open('图像6.jpg')
PilImg_Subtract = ImageChops.subtract(PilImg_Subtract1,
                                      PilImg_Subtract2, 2.0, 30)
# PilImg_Subtract.show()

# 图像混合操作(blend)。
# ImageChops.blend(image1, image2, alpha) ⇒ image
PilImg_Blend1 = Image.open('图像5.jpg')
PilImg_Blend2 = Image.open('图像6.jpg')
PilImg_Blend3 = ImageChops.blend(PilImg_Blend1, PilImg_Blend2, 0.25)
# PilImg_Blend3.show()

# 图像复合操作(composite)。
# ImageChops.composite(image1, image2, mask) ⇒ image
PilImg_Composite0 = Image.open('图像5.jpg')
PilImg_Composite1 = PilImg_Composite0.convert('RGB')
PilImg_Composite4 = Image.open('图像6.jpg')
PilImg_Composite2 = PilImg_Composite4.convert('RGB')
PilImg_Composite5 = PilImg_Composite2.copy()
PilImg_Composite3 = PilImg_Composite5.convert('1')  # "1"、"L"、"RGBA"
PilImg_Composite6 = ImageChops.composite(PilImg_Composite1,
                                         PilImg_Composite2, PilImg_Composite3)
# PilImg_Composite6.show()

# ImageChops.offset(image, xoffset, yoffset) ⇒ image
# ImageChops.offset(image, offset) ⇒ image
# Returns a copy of the image where data has been
# offset by the given distances.
# Data wraps around the edges. If yoffset is omitted,
# it is assumed to be equal to xoffset.

# 图像绘制库
Mode_NewImg = "RGB"
Width_NewImg = 1000
Height_NewImg = 1000
Color_NewImg = "#78b8e7"
PilImg_Draw = Image.new(Mode_NewImg, (Width_NewImg, Height_NewImg),
                        Color_NewImg)

# 绘制图像
Draw = ImageDraw.Draw(PilImg_Draw)

# 绘制圆弧(arc)
# draw.arc(xy, start, end, options)
# draw.arc([x1, y1, x2, y2], startAngle, endAngle, options)
# 在左上角坐标为(x1,y1),右下角坐标为 (x2,y2)的矩形区域内,
# 以starangle为起始角度,endAngle为终止角度,
# 截取圆O的一部分圆弧绘制出来。如果[x1,y1,x2,y2]区域不是正方形,
# 则在该区域内的最大椭圆中根据角度截取片段。注意:
# [x1,y1,x2,y2]规定矩形框的水平中位线为0度角,
# 角度顺时针变大(与数学坐标系规定方向相反),
# 绘制一个90度蓝色圆弧
Draw.arc((0, 0) + (PilImg_Draw.width / 2, PilImg_Draw.height / 2),
         30, 150, fill="blue")
# 绘制一个红色上半圆弧
Draw.arc((0, 0) + (PilImg_Draw.width / 2, PilImg_Draw.height / 2),
         180, 360, fill="red")
# 绘制一个右半椭圆,只需改区域大小为长方形
Draw.arc((0, 0) + (PilImg_Draw.width / 2, PilImg_Draw.height / 2 - 150),
         90, 270, fill="green")

# 绘制正弦(chord)
# Draw.chord(xy, start, end, options)
# 用法与arc相同,用来画圆从startAngle到endAngle的弦。
# 绘制一条弦
Draw.chord((PilImg_Draw.width / 2, 0) +
           (PilImg_Draw.width, PilImg_Draw.height / 2),
           270, 360, outline="red")
# 绘制弦并且将弦与弧包围区域涂色
Draw.chord((PilImg_Draw.width / 2, 0) +
           (PilImg_Draw.width, PilImg_Draw.height / 2),
           90, 180, fill="red")

# 绘制椭圆(ellipse)
# draw.ellipse(xy, options)
Draw.ellipse((PilImg_Draw.width / 2, 100) +
             (PilImg_Draw.width, PilImg_Draw.height / 2 - 100),
             outline=128)
Draw.ellipse((PilImg_Draw.width / 2, 100) +
             (PilImg_Draw.width, PilImg_Draw.height / 2 - 100),
             fill="blue")

# 绘制直线(line)
# draw.line(xy, options)
Draw.line((0, 0) + PilImg_Draw.size, fill=128)
Draw.line((0, PilImg_Draw.size[1], PilImg_Draw.size[0], 0), fill=128)

# 绘制起始角度间的扇形区域(pieslice)
# draw.pieslice(xy, start, end, options)
# 绘制180度到210度的扇形区域轮廓
Draw.pieslice((0, PilImg_Draw.height / 2) +
              (PilImg_Draw.width / 2, PilImg_Draw.height),
              180, 210, outline=128)
# 绘制60度到90度的扇形区域
Draw.pieslice((0, PilImg_Draw.height / 2) +
              (PilImg_Draw.width / 2, PilImg_Draw.height),
              60, 90, fill="blue")

# 绘制点(point)
# draw.point(xy, options)
Draw.point((PilImg_Draw.width / 2, PilImg_Draw.height / 2 + 10),
           fill="black")

# 绘制多边形(polygon)
# draw.polygon(xy, options)
Draw.polygon([(200, 200), (600, 300), (300, 600)],
             outline="green")
Draw.polygon([(300, 300), (500, 300), (300, 500), (500, 500)],
             fill="#34a2b6")

# 绘制矩形(rectangle)
# draw.rectangle(box, options)
Draw.rectangle((750, 750, 850, 850), outline="red")
Draw.rectangle((850, 850, 900, 920), fill="#9934c5")

# 加载bitmap字体
# TextFont = ImageFont.truetype('Arial.ttf', 36)
# TextFont = ImageFont.load("arial.pil")

# 绘制文本(text)
# draw.text(position, string, options)
Text = "I love python!"
Draw.text([600, 600], Text, "red")
# Draw.text((800, 800), Text, font=TextFont)

# 获取文本位置
# width, height = Draw.textsize(Text, "red")
# print("文本位置:", width, height)
# PilImg_Draw.show()
del Draw

# 图像增强模块(ImageEnhance Module)
PilImg_Enhance = Image.open('图像5.jpg')

# 颜色增强
# ImageEnhance.Color(image) ⇒ Color enhancer instance
PilImg_Color = ImageEnhance.Color(PilImg_Enhance)
# for i in range(5):
#    factor = i * 4.0
#    PilImg_Color.enhance(factor).show("Color %f" % factor)

# 亮度增强
# ImageEnhance.Brightness(image) ⇒ Brightness enhancer instance
# PilImg_Brightness = ImageEnhance.Brightness(PilImg_Enhance)
# for i in range(5):
#    factor = i * 2.0
#    PilImg_Brightness.enhance(factor).show("Brightness %f" % factor)

# 对比度增强
# ImageEnhance.Contrast(image) ⇒ Contrast enhancer instance
# PilImg_Contrast = ImageEnhance.Contrast(PilImg_Enhance)
# for i in range(5):
#    factor = i * 2.0
#    PilImg_Contrast.enhance(factor).show("Contrast %f" % factor)

# 锐度增强
# ImageEnhance.Sharpness(image) ⇒ Sharpness enhancer instance
# PilImg_Sharpness = ImageEnhance.Sharpness(PilImg_Enhance)
# for i in range(5):
#    factor = i * 4.0
#    PilImg_Sharpness.enhance(factor).show("Sharpness %f" % factor)

# 截取屏幕
Box = (300, 300, 900, 900)
PilImg_Grab1 = ImageGrab.grab()
PilImg_Grab2 = ImageGrab.grab(Box)
# PilImg_Grab2.show()

# 获取剪切板图像
PilImg_Grab3 = ImageGrab.grabclipboard()
# if isinstance(PilImg_Grab, Image.Image):
#    PilImg_Grab3.show()
# else:
#    print("clipboard empty ...")

# 图像对比度最大化(规范化)(autocontrast)
# ImageOps.autocontrast(image, cutoff=0) ⇒ image
PilImg_Autocontrast1 = Image.open('图像5.jpg')
PilImg_Autocontrast = ImageOps.autocontrast(PilImg_Autocontrast1,
                                            cutoff=0.9)
# PilImg_Autocontrast.show()

# 灰度图像彩色化(colorize)
# ImageOps.colorize(image, black, white) ⇒ image
PilImg_Colorize1 = Image.open('图像5.jpg').convert('L')
PilImg_Colorize = ImageOps.colorize(PilImg_Colorize1,
                                    black=(100, 126, 189),
                                    white=(56, 146, 231))
# PilImg_Colorize.show()

# 删除边框像素(crop)
# ImageOps.crop(image, border=0) ⇒ image
PilImg_Crop1 = Image.open('图像5.jpg').convert('L')
PilImg_Crop2 = ImageOps.crop(PilImg_Crop1, border=500)
# PilImg_Crop1.show()

# 直方图均衡化(equalize)
# ImageOps.equalize(image) ⇒ image
PilImg_Equalize1 = Image.open('图像5.jpg')
PilImg_Equalize2 = ImageOps.equalize(PilImg_Equalize1)
# PilImg_Equalize2.show()

# 添加边框像素(expand)
# ImageOps.expand(image, border=0, fill=0) ⇒ image
PilImg_Expand1 = Image.open('图像5.jpg')
PilImg_Expand = ImageOps.expand(PilImg_Expand1, border=1, fill=1)
# PilImg_Expand.show()

# 垂直翻转图像(flip)
# ImageOps.flip(image) ⇒ image
PilImg_Flip1 = Image.open('图像5.jpg')
PilImg_Flip = ImageOps.flip(PilImg_Flip1)
# PilImg_Flip.show()

# 水平翻转图像(mirror)
# ImageOps.mirror(image) ⇒ image
PilImg_Mirror1 = Image.open('图像5.jpg')
PilImg_Mirror = ImageOps.mirror(PilImg_Mirror1)
# PilImg_Mirror.show()

# 将图像转换为灰度值图像(grayscale)
# ImageOps.grayscale(image) ⇒ image
PilImg_Grayscale1 = Image.open('图像5.jpg')
PilImg_Grayscale = ImageOps.grayscale(PilImg_Grayscale1)
# PilImg_Grayscale.show()

# 反转(取反)图像(invert)
# ImageOps.invert(image) ⇒ image
PilImg_Invert1 = Image.open('图像5.jpg')
PilImg_Invert2 = ImageOps.invert(PilImg_Invert1)
# PilImg_Invert2.show()

# 减少每个颜色通道的位数(posterize)
# ImageOps.posterize(image, bits) ⇒ image
PilImg_Posterize1 = Image.open('图像5.jpg')
PilImg_Posterize = ImageOps.posterize(PilImg_Posterize1, bits=2)
# PilImg_Posterize.show()

# 将给定阈值之上所有像素值取反(solarize)
# ImageOps.solarize(image, threshold=128) ⇒ image
PilImg_Solarize1 = Image.open('图像5.jpg')
PilImg_Solarize = ImageOps.solarize(PilImg_Solarize1, threshold=250)
# PilImg_Solarize.show()

# 将调色板添加到图像中 (序列语法,Sequence Syntax)
# palette = []
# for i in range(256):
#    palette.extend((i, i, i)) # grayscale wedge
# assert len(palette) == 768
# im.putpalette(palette)

# 将调色板添加到图像中 (未支持)
# import ImagePalette
# palette = ImagePalette.ImagePalette("RGB")
# palette.putdata(...)
# im.putpalette(palette)

# 使用Resize/Convert获取调色板内容
# assert im.mode == "P"
# lut = im.resize((256, 1))
# lut.putdata(range(256))
# lut = lut.convert("RGB").getdata()
# lut now contains a sequence of (r, g, b) tuples

# 计算图像统计信息
# PilImg_Stat1 = Image.open('图像3.jpg')
# PilImg_Stat = ImageStat.Stat(PilImg_Stat1)
# 计算图像每个通道的最小值和最大值(stat.extrema)
# print("STAT最小值和最大值:", PilImg_Stat.extrema)
# 计算图像的像素总数(stat.count)
# print("STAT像素总数:", PilImg_Stat.count)
# 计算图像所有像素的总和(stat.sum)
# print("STAT像素总和:", PilImg_Stat.sum)
# 计算图像所有像素的平方和(stat.sum2)
# print("STAT像素平方和:", PilImg_Stat.sum2)
# 计算图像的平均像素值(stat.mean)
# print("STAT平均像素值:", PilImg_Stat.mean)
# 计算图像的像素中值(stat.median)
# print("STAT像素中值:", PilImg_Stat.median)
# 计算图像的RMS(均方根)(stat.rms)
# print("STAT均方根:", PilImg_Stat.rms)
# 计算图像的方差(stat.var)
# print("STAT方差:", PilImg_Stat.var)
# 计算图像的标准差(stat.stddev)
# print("STAT标准差:", PilImg_Stat.stddev)

# Matplotlib 绘图示例。 带有坐标轴和不带坐标轴的包含点和一条线段的图像
# 使坐标轴不显示
# axis('off')
# 读取图像到数组中
# im = array(Image.open('empire.jpg'))
# 绘制图像
# imshow(im)
# 一些点
# x = [100,100,400,400]
# y = [200,500,200,500]
# 使用红色星状标记绘制点
# plt.plot(x, y, 'r*')
# 绘制连接前两个点的线
# plt.plot(x[:2], y[:2])
# 添加标题,显示绘制的图像
# plt.title('Plotting: "empire.jpg"')
# plot(x,y) # 默认为蓝色实线
# plot(x,y,'r*') # 红色星状标记
# plot(x,y,'go-') # 带有圆圈标记的绿线
# plot(x,y,'ks:') # 带有正方形标记的黑色虚线
# 基本颜色格式命令:'b' 蓝色;'g' 绿色;'r' 红色;'c' 青色;'m' 品红;'y' 黄色;'k' 黑色;'w' 白色
# 基本线型格式命令:'-' 实线;'--' 虚线;':' 点线
# 基本绘制标记格式命令:'.' 点;'o' 圆圈;'s' 正方形;'*' 星形;'+' 加号;'x' 叉号
# show()

# 用 Matplotlib 绘制图像等轮廓线和直方图
# 读取图像到数组中
# im = array(Image.open('empire.jpg').convert('L'))
# 新建一个图像
# figure()
# 不使用颜色信息
# gray()
# 在原点的左上角显示轮廓图像
# contour(im, origin='image')
# axis('equal')
# axis('off')
# figure()
# hist(im.flatten(),128)
# show()

# 交互式标注
# im = array(Image.open('empire.jpg'))
# imshow(im)
# print("Please click 3 points")
# x = ginput(3)
# print("you clicked:", x)
# show()

# 图像数组表示
# %clear
# im = array(Image.open('empire.jpg'))
# print(im.shape, im.dtype)
# im = array(Image.open('empire.jpg').convert('L'),'f')
# print(im.shape, im.dtype)

# 切片方式访问数组
# im[i,:] = im[j,:] # 将第 j 行的数值赋值给第 i 行
# im[:,i] = 100 # 将第 i 列的所有数值设为 100
# im[:100,:50].sum() # 计算前 100 行、前 50 列所有数值的和
# im[50:100,50:100] # 50~100 行, 50~100 列(不包括第 100 行和第 100 列)
# im[i].mean() # 第 i 行所有数值的平均值
# im[:,-1] # 最后一列
# im[-2,:] (or im[-2]) # 倒数第二行

# 灰度变换
# im1 = array(Image.open('empire.jpg').convert('L'))
# im2 = 255 - im1 # 对图像进行反相处理
# im3 = (100.0/255) * im1 + 100 # 将图像像素值变换到 100...200 区间
# im4 = 255.0 * (im1/255.0)**2 # 对图像像素值求平方后得到的图像
# figure()
# imshow(im1)
# plt.title('fanxiangchuli')
# figure()
# imshow(im2)
# figure()
# imshow(im3)
# figure()
# imshow(im4)
# print(int(im1.min()), int(im1.max()))
# array() 变换的相反操作
# pil_im = Image.fromarray(im)
# pil_im = Image.fromarray(uint8(im))

im = array(Image.open('empire.jpg').convert('L'))
im2, cdf = imtools.histeq(im)

 


本文链接: http://www.dtmao.cc/news_show_450096.shtml

附件下载

相关教程

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?