用Python将图片转换为有趣的散点图 |
您所在的位置:网站首页 › 矢量图转灰度图 › 用Python将图片转换为有趣的散点图 |
本篇文章介绍如何使用python将图片转换为散点图,如下面左边图片转换为右边的散点图的形式。这样可以实现一些有趣的应用。 基本思路:读入原始图片→压缩→转化为灰度图→二值化灰度图→获得灰度值为0(黑色)的点的坐标序列→按照坐标序列绘制散点图。 主要用到的库:sklearn preprocessing; skimage io,transform; matplotlib.pyplot; kimage.color rgb2gray. 代码实现: import numpy as np from sklearn import preprocessing from skimage import io,transform import matplotlib.pyplot as plt from skimage.color import rgb2gray import os #读取原始图片 path='D:\\PythonStudy\\images\\' os.makedirs(path) img0 = io.imread(path+'\\aixin.jpg') print('img0彩色图像的形状为:',img0.shape) img0彩色图像的形状为: (175, 190, 3) #显示原始图片 io.imshow(img0) io.show() #将彩色图像转化为灰度图像,压缩,并显示 img_gray = rgb2gray(transform.rescale(img0, 0.3))#压缩比例 io.imshow(img_gray) io.show() print('img_gray灰度图像的形状为:',img_gray.shape) img_gray灰度图像的形状为: (52, 57) #二值化灰度图像数据,threshold为二值化灰度阈值 binarizer = preprocessing.Binarizer(threshold=.45).\ fit(img_gray) img_gray_binary=binarizer.transform(img_gray) io.imshow(img_gray_binary) #获得灰度值为0的元素索引 scatter_idx=np.array(np.where(img_gray_binary==0)) #绘制灰度值为0的元素散点图 plt.figure(figsize=(6,6),frameon=False) plt.scatter(scatter_idx[1],scatter_idx[0],marker='.')#显示灰度图像 plt.show 可以看出,输出的图片与原始图片反向,需要将纵轴反向。最终的图像并不需要坐标轴,因此可以关闭坐标轴。 #图像反向,关闭坐标轴 plt.figure(figsize=(5,5),frameon=False) plt.scatter(scatter_idx[1],scatter_idx[0],marker='.')#显示灰度图像 ax = plt.gca() ax.invert_yaxis()#y轴反向 plt.axis('off')#关闭坐标轴 plt.show 最终的效果如下图所示。 可以通过调节原始图片的压缩比和灰度图像的二值化阈值来改变转换效果。最后再上两张转换的其它图片。 用这些图片作为头像是不是很酷?! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |