人工智能最近很火,比如拍照就能识别是什么物品,文字识别等等,今天我们就来讲一个简单的,几行代码实现识别
我们的算法是基于KMeans聚类算法的图像分割技术
代码分三部分,第一部分导入相关库
import numpy as np
import PIL.Image as image
from sklearn.cluster import KMeans
第二部分导入图像文件并且以像素矩阵形式提供
def loadData(filePath):
f = open(filePath,'rb')
data = []
img = image.open(f)
m,n = img.size
for i in range(m):
for j in range(n):
x,y,z = img.getpixel((i,j))
data.append([x/256.0,y/256.0,z/256.0])
f.close()
return np.mat(data),m,n
第三部分灰度图像处理公式(固定好的直接套用)
imgData,row,col = loadData('kmeans/bull.jpg')
label = KMeans(n_clusters=4).fit_predict(imgData)
label = label.reshape([row,col])
pic_new = image.new("L", (row, col))
for i in range(row):
for j in range(col):
pic_new.putpixel((i,j), int(256/(label[j]+1)))
pic_new.save("result-bull-4.jpg", "JPEG")
效果图
处理前
处理后
全部代码
import numpy as npimport PIL.Image as imagefrom sklearn.cluster import KMeans def loadData(filePath): f = open(filePath,'rb') data = [] img = image.open(f) m,n = img.size for i in range(m): for j in range(n): x,y,z = img.getpixel((i,j)) data.append([x/256.0,y/256.0,z/256.0]) f.close() return np.mat(data),m,n imgData,row,col = loadData('kmeans/bull.jpg')label = KMeans(n_clusters=4).fit_predict(imgData) label = label.reshape([row,col])pic_new = image.new("L", (row, col))for i in range(row): for j in range(col): pic_new.putpixel((i,j), int(256/(label[j]+1)))pic_new.save("result-bull-4.jpg", "JPEG") |