文章目录
1. 识别与图像处理类
1.1 基于python的百度云免费文字识别OCR
- 注册并登录百度智能云网站
- 点击网页右上角
管理控制台
; - 点击左侧
产品服务
,选择文字识别;
- 创建一个文字识别应用;
- pip 安装使用 Python SDK:
pip install baidu-aip
- 接下来遵循官方文档操作就OK,🔗官方文档;
除了百度 OCR,还有其他云计算 OCR 可用:
微软Azure 图像识别:https://azure.microsoft.com/zh-cn/services/cognitive-services/computer-vision/
有道智云文字识别:http://aidemo.youdao.com/ocrdemo
阿里云图文识别:https://www.aliyun.com/product/cdi/
腾讯OCR文字识别: https://cloud.tencent.com/product/ocr
文章目录
1.2 PIL(Pillow)
PIL(Python Imaging Library) 是Python中一个强大的图像处理库,但目前其只支持到Python2.7 ,Pillow是PIL的一个分支,虽是分支但是其与PIL同样也具有很强的图像处理库,重点是支持python3.x,因此在Python3.x中应导入Pillow
模块,但代码中仍然使用 import PIL
1.2.1 加载图像
Image.open()
加载图像,支持加载 PNG、JPEG、GIF格式图片;save()
保存图像;
from PIL import Image
catIM = Image.open('zophie.png') # 创建 Image 对象
print(catIM.size) # 获取图片尺寸
print(catIM.filename) # 获取图片的文件名
print(catIM.format) # 简述图片的格式
print(catIM.format_description) # 详述图片的格式
catIM.save('otherfilename.png') # 保存图片
运行结果:
(400, 533)
zophie.png
JPEG
JPEG (ISO 10918)
1.2.2 灰度转换
convert('1')
转换图像灰度,参数分别有 ‘1’, ‘L’, ‘P’, ‘RGB’, ‘RGBA’, ‘CMYK’, ‘YCbCr’, ‘I’, ‘F’ ;
from PIL import Image
catIM = Image.open('20181013001123481.jpg')
catIM = catIM.convert('1') # 转换图像颜色
# catIM = Image.open('20181013001123481.jpg').convert('L')
catIM.show()
1.2.3 新建图像
Image.new()
新建图像;
from PIL import Image
# 创建一个有 100*200 像素大小、带有紫色背景的 Image 对象
im = Image.new('RGBA', (100,200), 'purple')
im.save('purpleImage.png')
# 创建一个有 20*20 像素大小、无指定颜色的 Image 对象
im2 = Image.new('RGBA', (20,20)) # 无指定颜色即 RGBA 值为(0,0,0,0)即具有透明背景
im2.save('2020.png')
1.2.4 裁剪图像
crop()
裁剪 BOX 坐标元组内的图像;
裁剪图像即在图像内选择一个区域,并删除区域以外的其他图像;
from PIL import Image
catIM = Image.open('zophie.png') # 创建 Image 对象
croppedIm = catIM.crop((200,200,565,560))
croppedIm.save('cropped.png')
1.2.5 复制和粘贴图像
尽管 Pillow 中复制和粘贴图像的方法叫 copy()
和 paste()
,但并不使用计算机的剪贴板;
copy()
复制图像;Image.paste(im, box=None, mask=None)
粘贴图像到当前图像;- box - 【可选】四元元组或二元元组,提供图像粘贴的区域或坐标,缺省值为(0,0),即粘贴图像到源图像的左上角;
- mask - 【可选】
from PIL import Image
catIM = Image.open('zophie.png') # 创建 Image 对象
catCopyIm = catIM.copy() # 创建 Image 副本对象
faceIm = catIM.crop((335,345,565,560))
catCopyIm.paste(faceIm,(0,0)) # 粘贴 faceIm到 catCopyIm
catCopyIm.save('catCopyIm.png')
1.2.6 调整图片大小
resize()
重新调整图片的大小,该方法不会在原图上修改 Image 对象,而是返回一个新的 Image 对象;thumbnail((128,128))
创建缩略图,接受一个元组参数,与 resize 不同的是它只能缩小而不能放大图像;
from PIL import Image
catIM = Image.open('zophie.png') # 创建 Image 对象
width,height = catIM.size
quartersizedIm = catIM.resize((int(width/2),int(height/2))) # 图片尺寸减半
quartersizedIm.show()
catIM.thumbnail((128,128)) # 创建缩略图
catIM.show()
1.2.7 旋转图像
rotate()
对图像以逆时针旋转对应的角度,默认保留原图尺寸,但可传入关键字参数expand=True
来保留处理后的图片尺寸;
from PIL import Image
catIM = Image.open('zophie.png') # 创建 Image 对象
catIM.rotate(90).save('rotate90.png') # 保留原图的尺寸
catIM.rotate(90, expand=True).save('rotate90.png') # 保留图片处理后的尺寸
1.2.8 镜像翻转图像
transpose()
镜像翻转图像;
from PIL import Image
catIM = Image.open('zophie.png') # 创建 Image 对象
catIM.transpose(Image.FLIP_LEFT_RIGHT).save('transposeLR.png') # 左右翻转
catIM.transpose(Image.FLIP_TOP_BOTTOM).save('transposeUD.png') # 上下翻转
catIM.transpose(Image.FLOYDSTEINBERG).save('transposeLRUD.png') # 左右上下翻转
1.2.9 更改单个像素
from PIL import Image, ImageColor
im = Image.new('RGBA', (100,100))
print(im.getpixel((0,0))) # 获取某像素RGBA
for x in range(100):
for y in range(50):
im.putpixel((x,y),(210,210,210)) # 设置某像素 RGBA
for x in range(100):
for y in range(50,100):
im.putpixel((x,y),ImageColor.getcolor('chocolate','RGBA'))
print(im.getpixel((0,0)))
print(im.getpixel((0,50)))
im.save('putpixel.png')
1.2.10 获取某颜色对应的 RGBA 值
from PIL import ImageColor
print(ImageColor.getcolor('red','RGBA'))
print(ImageColor.getcolor('chocolate','RGBA')) # 获取巧克力色的 RGBA
运行结果:
(255, 0, 0, 255)
(210, 105, 30, 255)
1.2.11 ImageDraw 图像绘画
PIL.ImageDraw.ImageDraw.point(xy,fill = None )
绘点;xy
– 点坐标,如 [(x, y), (x, y), …] 或 x,y 坐标的列表,如 [x, y, x, y, …];fill
– 填充颜色,可是颜色字符串如 ‘red’ 或 RGBA 元组;
PIL.ImageDraw.ImageDraw.line(xy, fill=None, width=0, joint=None)
绘直线;xy
–直线的起始点,多于两个点则为直线的折点,如 [(x, y), (x, y), …] 或 x,y 坐标的列表,如 [x, y, x, y, …];fill
–同上;width
– 线宽;
PIL.ImageDraw.ImageDraw.polygon(xy,fill = None,outline = None )
绘多边形;xy
– 多边形的点;如 [(x, y), (x, y), …] 或坐标的列表,如 [x, y, x, y, …];outline
– 同上;fill
– 同上;
PIL.ImageDraw.ImageDraw.rectangle(xy, fill=None, outline=None, width=0)
绘矩形;xy
– 矩形对角线的起点与终点,如[(x0, y0), (x1, y1)] or [x0, y0, x1, y1].;outline
– 同上;fill
– 同上;width
– 轮廓线的宽度;
PIL.ImageDraw.ImageDraw.ellipse(xy, fill=None, outline=None, width=0)
绘椭圆;xy
–提供一个矩形的对角线坐标,在该矩形内绘椭圆,若矩形为正方形,则绘一个圆,如[(x0, y0), (x1, y1)] or [x0, y0, x1, y1];outline
– 同上;fill
– 同上;width
– 同上;
from PIL import Image, ImageDraw
im = Image.new('RGBA', (2000,2000), 'white')
draw = ImageDraw.Draw(im) # 创建 ImageDraw 对象
draw.point([(1,1),(2,2),(3,3)], fill='red') # 绘点
draw.line([(10,10),(20,20),(30,30)],fill='green',width=2) # 绘线
draw.rectangle([(1000,1000),(1500,1800)],fill='orange',outline='black',width=10) # 绘矩形
draw.ellipse([(200,100),(300,300)],fill='yellow',outline='red',width=50) # 绘椭圆
draw.polygon([(100,200),(1000,400),(800,600),(1000,2000)],fill='red',outline='blue',) # 绘多边形
im.show()
1.2.12 ImageFont 绘制文本
PIL.ImageFont.load(filename)
加载字体文件,返回字体对象PIL.ImageFont.truetype(font=None, size=10, index=0, encoding='', layout_engine=None)
加载 TrueType 或 OpenType 字库文件或类文件;font
– TrueType 或 OpenType 文件名或类文件名. 若找不到该文件,Windows 的加载器会在 Windows 的字体库中查找;size
– 字体大小,以磅为单位;encoding
– 字体编码,默认为 Unicode;layout_engine
– 布局引擎;
PIL.ImageDraw.Draw.text()
- 文本起始坐标;
- 文本内容字符串;
fill
- 字体填充颜色;
from PIL import ImageFont,ImageDraw,Image
import os
im = Image.new('RGBA',(200,200),'white')
draw = ImageDraw.Draw(im) # 创建 ImageDraw 对象
draw.text((20,150),'Hellow',fill='purple') # 绘制文本
fontsFolder = 'FONT_FOLDER'
arialFont = ImageFont.truetype(os.path.join(fontsFolder,'arial.ttf'),32) # 加载 truetype 字库,设置字体大小
draw.text((100,150),'Yuen',fill='red',font=arialFont) # 绘制文本,使用 truetype 字库
im.show()
1.3 Matplotlib
1.3.1 在图像上绘制点和线
from PIL import Image # 安装 Pillow模块
import pylab # 安装 matplotlib 模块
import numpy # 安装 numpy 模块
x=[100,200,400,150] # 坐标值
y=[20,200,200,350]
im = Image.open('zophie.png')
ima = numpy.array(im) # 读取图像到数组中
print(ima)
pylab.imshow(ima) # 绘制图像
# 绘图示例
# pylab.plot(x,y) # 默认使用蓝色实线连接标记点
pylab.plot(x,y,'r*') # 绘制红色星状标记点
# pylab.plot(x,y,'go-') # 使用圆圈标记点的绿线(覆盖原标记点)(带减号'-'则绘制连接标记点的线,不带就绘点)
# pylab.plot(x,y,'ks-') # 使用黑色正方形标记点(覆盖原标记点)
pylab.plot(x[:2],y[:2]) # 绘制连接前两个点的线
pylab.title('plotting:"empire.jpg"')
# pylab.axis('off') # 不显示坐标轴
pylab.show()
运行结果:
参数 | 颜色 |
---|---|
b | 蓝色 |
g | 绿色 |
r | 红色 |
c | 青色 |
m | 品红 |
y | 黄色 |
k | 黑色 |
w | 白色 |
参数 | 线型格式 |
---|
- |虚线
– |虚线
: |点线
参数 | 标记点格式 |
---|---|
. | 点 |
o | 圆圈 |
s | 正方形 |
- |星形
- |加号
x |叉号
1.3.2 图像轮廓线和直方图
from PIL import Image
import pylab # 安装 matplotlib 模块
import numpy
im = numpy.array(Image.open('zophie.png').convert('L')) # 图像灰度化
pylab.figure() # 新建一个图像
pylab.gray() # 不使用颜色信息
pylab.contour(im,origin='image') # 在原点的左上角显示轮廓图像
pylab.axis('equal')
pylab.axis('off')
pylab.show()
图像的直方图用来表征图像像素值的分布情况,用一定数目的小区间来执行表征像素值的范围,该灰度图像的直方图可用 hist()
函数绘制,它只接受一维数组作为输入,所以在绘直方图前,必须先对图像进行flatten()
处理,它将任意数组按照行有限准则转换成一维数组。
from PIL import Image
import pylab # 安装 matplotlib 模块
import numpy
ima = Image.open('zophie.png').convert('L') # 图像灰度化
im = numpy.array(ima)
pylab.figure() # 新建一个图像
pylab.hist(im.flatten(),128) # 绘制图像直方图,第二个参数指定了小区间的数目
pylab.show()
1.3.3 交互式标注
from PIL import Image
import pylab # 安装 matplotlib 模块
import numpy
im = numpy.array(Image.open('zophie.png')) # 读取图像到数组中
pylab.imshow(im)
print('Please click 3 points...')
x = pylab.ginput(3) # 交互式标注,得到的坐标值保存在列表 x 中
print('you clicked: ',x)
1.4 Numpy
Numpy是 Python 中的一个线性代数库,可帮助实现数组中重要的线性代数计算操作,如矩阵乘积、转置、解方程组、向量乘积和归一化,为图像变形、对变化进行建模、图像分类、图像聚类等提供基础;
参考:NumPy 中文、菜鸟教程
1.4.1 图像数组表示
from PIL import Image
import numpy
im1 = numpy.array(Image.open('zophie.png'))
print(im1.shape,im1.dtype)
im2 = numpy.array(Image.open('zophie.png').convert('L'),'f')
print(im2.shape,im2.dtype)
运行结果:
(377, 502, 3) uint8
(377, 502) float32
im1.shape
的结果为一个元组,内含图像数组的大小(行,列,颜色通道),im1.dtype
的结果为数组元素的数据类型
uint8
表示无符号八位整数;而在灰度图像中没有颜色信息,所以在输出的元组中无颜色通道信息;
1.4.2 在图像数组中进行灰度转换
from PIL import Image
import numpy
im = numpy.array(Image.open('zophie.png').convert('L'))
print(int(im.min()),int(im.max()))
Image.fromarray(im).show() # array() 的反变换(数组转图像对象)
im2 = 255 - im # 对图像进行反相处理
print(int(im2.min()),int(im2.max()))
Image.fromarray(im2).show()
im3 = (100.0/255) * im + 100 # 将图像像素值变换到100~200区间
print(int(im3.min()),int(im3.max()))
Image.fromarray(im3).show()
im4 = 255.0 * (im/255.0) ** 2 # 对图像像素值求平方后得到的图像
print(int(im4.min()),int(im4.max()))
Image.fromarray(im4).show()
1.* 附
1.*.1 RGBA
RGBA 是一组数字,计算机通常用 RGBA 值来指定像素的颜色,RGBA 分别表示红、绿、蓝、透明度(alpha) ,它们的取值范围都是 0(无)到255(最大),在 RGBA 中纯黑色表示无任何颜色,其值为(0,0,0,255) ,而像素是屏幕上能显示一种颜色的最小点;
扩展:
- RGB:光学三原色(三原色即不可再分解的三组基本颜色),即红、绿、蓝;
- CMYK:颜料三原色,即品红、黄、青;
1.*.2 坐标与 BOX 元组
图像的坐标用一个含4个值的 BOX元组表示,即 (x,top,y,bottom) ,坐标以屏幕左上角为原点,无负坐标值,如下图的坐标为(3, 1, 9, 6);
参考:
https://blog.csdn.net/Barry_J/article/details/79528672
https://blog.csdn.net/Barry_J/article/details/79593175
https://blog.csdn.net/fu6543210/article/details/83240024
https://www.cnblogs.com/xuxugui/p/9815237.html
1.* 笔记
pip insatll pytesseract
brew install tesseract
tesseract --list-langs
def screen_shot():
time.sleep(2) # delay 2s
unit1_shot = pyautogui.screenshot('last_sample.png', region=(160, 372, 280, 25)) # tuple: (left, up, width, height )
unit1_shot.save('unit1.png')
unit2_shot = pyautogui.screenshot('last_sample.png', region=(788, 372, 210, 25)) # tuple: (left, up, width, height )
unit2_shot.save('unit2.png')
def screenShot():
screen_co_dict = {
'screen_x': 0,
'screen_y': 0
}
time.sleep(2)
pyautogui.moveRel(4096,4096)
time.sleep(0.5)
screen_co_dict['screen_x'], screen_co_dict['screen_y'] = pyautogui.position()
screen_shot_original = pyautogui.screenshot()
screen_shot = screen_shot_original.resize((1279,799))
co_dict = {
'unit1_x': (160/1279) * screen_co_dict['screen_x'], 'unit1_y': (372/799) * screen_co_dict['screen_y'],
'unit2_x': (788/1279) * screen_co_dict['screen_x'], 'unit2_y': (372/799) * screen_co_dict['screen_y']
}
screen_shot.save('last_sn_sample.png')
unit1_shot = pyautogui.screenshot('last_sample.png', region=(co_dict['unit1_x'], co_dict['unit1_y'], 280, 25)) # tuple: (left, up, width, height )
# unit1_shot.show()
unit1_shot.save('unit1.png')
unit2_shot = pyautogui.screenshot('last_sample.png', region=(co_dict['unit2_x'], co_dict['unit2_y'], 210, 25)) # tuple: (left, up, width, height )
# unit2_shot.show()
unit2_shot.save('unit2.png')
def finish_tips():
pyautogui.moveTo(639, 400)
for i in range(5):
pyautogui.moveRel(50, 0)
pyautogui.moveRel(-50, 0)
def colour_rec2():
pass_colour = ((121, 255, 209, 255), (86, 253, 156, 255))
fail_colour = ((253, 111, 88, 255), (255, 131, 109, 255))
unit1_colour = Image.open('unit1.png').getpixel((0, 0))
unit2_colour = Image.open('unit2.png').getpixel((0, 0))
if unit1_colour == pass_colour[0] or unit1_colour == pass_colour[1]:
print('unit1: PASS')
elif unit1_colour == fail_colour[0] or unit1_colour == fail_colour[1]:
print('unit1: FAIL')
else:
print('unknown status for unit1')
if unit2_colour == pass_colour[0] or unit2_colour == pass_colour[1]:
print('unit2: PASS')
elif unit2_colour == fail_colour[0] or unit2_colour == fail_colour[1]:
print('unit2: FAIL')
else:
print('unknown status for unit2')
def main():
print('unit1 SN: ' + str(pytesseract.image_to_string(Image.open('unit1.png'), lang='eng')))
print('unit2 SN: ' + str(pytesseract.image_to_string(Image.open('unit2.png'), lang='eng')))
colour_rec2()
if __name__ == '__main__':
from PIL import Image
import time
import pyautogui
import pytesseract
screen_shot()
main()
finish_tips()
1.*.1 去水印脚本
打开PyCharm并新建一个工程,配置基础编译器, 新建Python文件,导入相应所需的模块。
开始编写代码。
# --------------- 使用说明 --------------- #
# 1. 将水印文件命名为 nasty.png ,并放置在桌面
# 2. 运行该脚本
# 3. 去水印完成,生成文件名为 pure.png
# --------------- End --------------- #
from PIL import Image
import os
os.chdir("C:\\Users\\username\\Desktop")
nastyImage = Image.open('nasty.png') # 打开 Image 对象
Imagelength,ImageWidth = nastyImage.size # 获取图片尺寸
# -------------- 遍历清除水印像素 -------------- #
for x in range(Imagelength):
for y in range(ImageWidth):
if (nastyImage.getpixel((x, y)) == (217,217,217,255) or nastyImage.getpixel((x, y)) == (216,216,216,255)):
nastyImage.putpixel((x,y),(255,255,255,255))
nastyImage.save('pure.png') # 保存图片 ^ - ^
保存并运行代码工程
1.*.2 画爱心
import time
words = input('请输出想要表达的文字:')
for item in words.split():
print('\n'.join([''.join([(item[(x-y) % len(item)] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(12, -12, -1)]))
time.sleep(1.5)
2. 爬虫
2.1 笔记
打开任意网站,按F12打开开发者工具,点“选择元素”或按Ctrl+B,选中爬取目标,如下图;
红框中为爬取目标,标签a
,class
,连接href
,及其字符串(后面灰色的文字);
3. 打包
python 脚本在没有搭载 python 环境的设备上是不能运行的,所以要将脚本打包成可执行的.exe
文件,降低脚本对环境的依赖性。
3.1 pyinstaller
3.1.1 安装 pyinstaller 模块包
- 在线安装,管理员运行Windows PowerShell,输入
pip3 install pyinstaller
- 安装完成后,输入
pip3 -v
查看是否安装成功;
3.1.2 使用 pyinstaller 打包 python 文件
- 到需要打包的目录,对着文件夹,按住Shift 键加鼠标右键,管理员运行Windows PowerShell
- 在窗口中输入
pyinstaller your_script_name.py
,其中,your_script_name.py
是要打包的Python 脚本文件的文件名 - 完成后,在生成的dist 文件夹中找到
.exe
文件 - 打包dist 文件夹即可,后续即可自己运行
.exe
文件,且文件夹内看不到源代码;
pyinstaller 打包参数:
-F:生成单个可执行文件,而不是一个包含多个文件的目录(默认情况下)。
-D:生成一个目录,其中包含可执行文件和其他依赖项文件。
–name:指定生成的可执行文件的名称。
–onefile:与-F相同,生成单个可执行文件。
–onedir:与-D相同,生成一个目录。
–hidden-import:指定要包含在打包中但不在Python脚本中明确导入的模块。
–clean:在打包之前清除先前生成的文件。
–noconsole:生成一个没有控制台窗口的GUI应用程序。
–windowed:生成一个没有控制台窗口的GUI应用程序(与–noconsole相同)。
如生成单个可执行文件,无控制台窗口的GUI应用程序,可输入:
pyinstaller -F --noconsole your_script_name.py
3.1.4 用 pipenv 创建虚拟环境,在虚拟环境中打包文件
如果已经安装过 pipenv 并且在虚拟环境中初始化过 python 环境,直接进入虚拟环境即可
初次搭建虚拟环境,需要安装
pipenv
- 管理员运行 cmd,输入以下指令
pip install pipenv
- 初始化 python 环境(最好先创建一个新的文件夹专门用来保存虚拟环境文件,然后
cd
跳转都该文件夹后再进行下面的操作,或者直接在待打包的工程中创建虚拟环境)pipenv --python x.x(当前 python 版本)
上述两步完成后,会在当前 cmd 操作目录生成一个名为
Pipfile
的虚拟环境文件,下次进入该虚拟环境直接从该文件所在的目录进入即可
- 进入虚拟环境(第一次进入会自动创建虚拟环境)
pipenv shell
退出虚拟环境:
exit
- 进入虚拟环境后,跟平常一样用
pip
安装各种库,输入 pyinstaller 打包指令即可
pip install wmi
pip install pywin32
pip install pyinstaller
`pip`安装工程中用到的库
# 安装所有`.py`文件中用到的库
# 注意`cd`跳转到`.py`文件所在工程路径
pyinstaller -F -w xxxx.py
4. 文件与路径处理
- 注意:
os
库是python 自带库,不需另外下载
4.1 返回到桌面路径
import os
def GetDesktopPath():
return os.path.join(os.path.expanduser("~"), 'Desktop')
if __name__ == '__main__':
desktopPath = GetDesktopPath() # 返回桌面路径并将路径返回
4.2 跳转到指定路径
import os
path = "..." # ... 表示目标路径
os.chdir(path) # 跳转到目标路径
注:在Windows 系统下,路径格式层级符应该用
/
,如文件夹处直接复制的路径为C:\Users\\Documents\WWork\\Che\File\20-09
则在Python 程序中应为C:/Users/Documents/WWork/Che/File/20-09