马赛克 拼图 python
In my previous article, I have explored an interesting format of representing images called as the bed sheet view, to develop some intuition behind Fourier Transforms.
在上一篇文章中 ,我探索了一种有趣的表示图像的格式,称为床单视图,以发展傅立叶变换背后的直觉。
This made me curious to explore alternate representations of images, which is the current theme. In this article, two fascinating approaches are explored to construct mosaic ‘art’ using python. The first approach uses emojis ( like 🏠,🔥, 😎…) and the second one uses ASCII characters.
这使我好奇地探索图像的替代表示形式,这是当前的主题。 在本文中,探索了两种引人入胜的方法来使用python构造马赛克“艺术”。 第一种方法使用表情符号(例如🏠,🔥,😎…),第二种方法使用ASCII字符。
Mosaics are traditionally patterns or images which are built using small regular or irregular pieces of stone or tile. A mosaic style of painting is called Pointillism where artists use blobs of paint to construct an entire image. Vincent Van Gogh, Georges Seurat, and Paul Signac are a few popular artists of this genre.
传统上,马赛克是使用规则或不规则的小块石头或瓷砖构建的图案或图像。 马赛克的绘画风格称为“点画派(Pointillism)”,艺术家使用颜料的斑点来构建整个图像。 Vincent Van Gogh,Georges Seurat和Paul Signac是该类型的一些受欢迎的艺术家。
Images are digital mosaics composed of pixels. Hence pixels can be replaced with other units to represent the same image. For example, emojis. More specifically, images of emojis.
图像是由像素组成的数字马赛克。 因此,可以用其他单位替换像素来表示同一图像。 例如,表情符号。 更具体地说,表情符号的图像。
Here, I have taken a directory of 1500 emojis. To substitute a pixel with an emoji, a fair comparison has to be established. So each emoji is reduced to a single RGB tuple by taking the mean of all pixels making up that individual emoji. Similarly, the means of all the emojis in the directory is evaluated. Now the image which we hope to convert to mosaic form is loaded and each pixel is replaced with an emoji which has the closest RGB value (nearest neighbor). The result would be as shown above!
在这里,我已建立了1500个表情符号的目录。 要用表情符号代替像素,必须建立合理的比较。 因此,通过获取构成单个表情符号的所有像素的平均值,可以将每个表情符号简化为单个RGB元组。 同样,将评估目录中所有表情符号的均值。 现在,我们希望转换为马赛克形式的图像已加载,并且每个像素都替换为具有最接近RGB值(最近邻)的表情符号。 结果将如上所示!
#imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mim
import matplotlib.pyplot as plt
from scipy import spatial
from matplotlib import cm
from PIL import Image
emoji_array = np.load("emojis_16.npy")
#emoji directory
#reference: https://github.com/sharmaabhishekk/emoji-mosaic-mpl
emoji_mean_array = np.array([ar.mean(axis=(0,1)) for ar in emoji_array])
#get mean of each emoji
tree = spatial.KDTree(emoji_mean_array)
#store them in a tree to search faster
G_sm = np.array(Image.open('bike.png').resize([20,20]).getdata()).reshape([20,20,3])/256
#open --> resize, smaller --> convert to an array --
#--> reshape to a 3d array --> normalize the pixel values
plt.figure()
plt.imshow(G_sm)
plt.title('Original Image')
indices = []
flattened_img = G_sm.reshape(-1, G_sm.shape[-1]) #flatten the array
#match the pixels with the closest resembling emoji
for pixel in flattened_img:
pixel_ = np.concatenate((pixel, [1]))
_, index=tree.query(pixel_)
indices.append(index)
#tree.query() finds the nearest neighbour index
emoji_matches = emoji_array[indices]
#from index get the corresponding emoji (flattened)
dim = G_sm.shape[0]
resized_ar = emoji_matches.reshape((dim, dim, 16, 16,4 ))
#reshape it to form the image. each emoji has the shape (16, 16, 4)
#note: 4 --> R, G, B, alpha
final_img = np.block([[[x] for x in row] for row in resized_ar])
#converts individual emoji patches (5 dimensional)
#into a complete image (3 dimensional) using numpy blocks
plt.figure()
plt.imshow(final_img)
plt.title('Emoji mosaic')
plt.savefig('bike_emojied.png')
A similar idea to transform images has existed since the 60s using ASCII characters, where printable characters are used instead of emojis to write text files which show images. Here is a website dedicated to ASCII art.
自60年代以来,就存在使用ASCII字符转换图像的类似想法,其中使用可打印字符代替表情符号来编写显示图像的文本文件。 这是一个致力于ASCII艺术的网站。
It used to be extremely popular since text was much faster to process. But, technology has caught up and ASCII art today remains only a relic for programming enthusiasts. In python, a succinct code can be developed to produce the following results.
由于文本处理起来要快得多,因此它曾经非常流行。 但是,技术日新月异,今天的ASCII艺术仍然只是编程爱好者的遗物。 在python中,可以开发一个简洁的代码来产生以下结果。
Here, an image is first converted to grey scale after being resized. A string of ASCII characters is constructed in the increasing order of the size of each character. It begins with solid characters like “#” and ends with smaller characters like “.”. Images can be coherently reproduced with a surprisingly small number of characters. The grey scale magnitude of each pixel is converted to the proportion of 256 (Upper limit). Based on this ratio, each pixel is replaced by a character in our original string of ASCII characters.
在此,图像在调整大小后首先转换为灰度。 ASCII字符字符串按每个字符大小的升序构造。 它以诸如“#”的实心字符开头,以诸如“。”的较小字符结尾。 图像可以以很少的字符连贯地再现。 每个像素的灰度级转换为256(上限)的比例。 基于此比率,每个像素将替换为我们原始ASCII字符串中的一个字符。
import string
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
%matplotlib inline
siz = 200
im = Image.open("bike.png").resize([siz, siz])
#open and resize
im2 = im.convert(mode = 'L')
#convert to greyscale
im4 = np.array(im2.getdata()).reshape([siz, siz])
#convert image to array (flattened) --> reshape
print('Image loaded.')
asci = r"QG@#$%?*+^)/;:!,'.` " #asci2 = r"B8&WM#YXQO{}[]()I1i!pao;:,. "
#ASCII directory
#check out the alternate verion using asci2!
im7 = []
for i in range(siz):
imtemp = ""
for j in range(siz):
imtemp+= asci[(len(asci)-1)*im4[i,j]//256]
im7.append(imtemp)
#get the proportion of 256 and replace with an ASCII charecter.
print('Image Converted.')
with open('bike_ascii.txt', 'w') as text:
for i in im7:
text.write(i)
text.write('\n')
print('Image written to .txt file.')
All the programs are also available on my GitHub.
所有程序也都可以在我的GitHub上找到 。
It is interesting to note that over 1500 emoji were used to make coherent replications of the original image. However, the second approach utilizes not more than two dozen ASCII characters to provide a valid visualization. It is not entirely a fair comparison, since the information related to color is lost in the later.
有趣的是,有超过1500个表情符号用于原始图像的连贯复制。 但是,第二种方法利用不超过两个打印的ASCII字符来提供有效的可视化效果。 这并不是完全公平的比较,因为与颜色有关的信息在以后会丢失。
It is also quite popular to convert videos into ASCII format, which provides an interesting visual effect, like the one used in the Matrix movies in the late 90s.
将视频转换为ASCII格式也很受欢迎,它提供了一种有趣的视觉效果,例如90年代后期在Matrix电影中使用的那种效果。
As always, reach out to me to continue the conversation on other interesting formats to represent images or to provide me with some feedback on the content.
与往常一样,与我联系以其他有趣的格式继续对话,以表示图像或为我提供有关内容的一些反馈。
翻译自: https://towardsdatascience.com/mosaic-art-using-python-422e9c5c130d
马赛克 拼图 python