python学习记录2022.7.15(2)
学习内容:
1、打开图片、二值化、读取文件夹的图片、处理图片。
2、机器学习算法有哪些、看文章、知网、机器学习算法。
学习产出:
图像二值化就是将图像上的像素点的“灰度值”设置为[0, 0, 0]或[255, 255, 255],即要么纯黑,要么纯白。
图片预处理
from PIL import Image
import numpy as np
img = Image.open("G:\python图片\IMG_20220622_112016.jpg")
img.show() #展示图片
print(img) # 输出图片的属性,不能输出矩阵形式
img=np.array(img) #将图像转为矩阵形式
#img=np.asarray(img)
print(type(img)) #显示类型
print(img.shape) #显示尺寸
print(img.shape[0]) #图片宽度
print(img.shape[1]) #图片高度
print(img.shape[2]) #图片通道数
print(img.size) #图片总的像素数
print(img.max()) #最大像素值
print(img.min()) #最小像素值
print(img.mean()) #像素平均值在这里插入代码片
结果图
图片预处理:灰度化-二值化
from PIL import Image
import numpy as np
img = Image.open("G:\python图片\IMG_20220622_112016.jpg")
img.show()
print(img) # 输出图片的属性,不能输出矩阵形式
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
Img = img.convert('L')
Img.show()
# 自定义灰度界限,大于这个值为黑色,小于这个值为白色
threshold = 100
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
# 图片二值化
photo = Img.point(table, '1')
photo.show()
碰到的问题
1.在将图像转为矩阵形式即img=np.array(img) 后,不能直接进行灰度化和二值化,会出现错误。
改正措施:改为img1=np.array(img)