这篇文章记录python像素处理的基本方法方法
做的是14年的建模A题嫦娥登陆。
其中一个问题是这样的
如何选择下面这个图(月球表面高度2400米处的照片)的嫦娥三号着陆点?
1. 读取图像
from scipy import misc
from scipy.misc import imread, imresize, imsave
import os
import seaborn as sns
import matplotlib.pyplot as plt
os.chdir('/Users/zhaohaibo/Desktop')
# 读取图像
pic = imread('pic2400.jpg')
pic.shape # (2300,2300)
pic.max() # 218
pic.min() # 0
pic.dtype # dtype('uint8')
# 使用sbs的palette变成一个带有颜色的图(目的?不知道。。)
sns.set()
sns.set_style("white")
pic2 = plt.imshow(pic)
plt.savefig('24003.jpg')
2.使用K-Means聚类
- img = cv2.imread(‘图片’)之后,直接就可以查看每个点的像素值
- 聚为8类,想象中大致就可以把平地那一类选出来了吧
import numpy as np
import cv2
from scipy import misc
from scipy.misc import imread, imresize, imsave
import os
import seaborn as sns
import matplotlib.pyplot as pl
os.chdir('/Users/zhaohaibo/Desktop')
#对rgb图像kmeans聚类
img = cv2.imread('24003.jpg')
Z = img.reshape((-1,3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
cv2.imwrite('k=8.jpg',res2)
分别是彩色和黑白的聚类结果。