1. 什么是蒙太奇马赛克图像
蒙太奇马赛克图像就是由N多个小图像拼接而成的大图像,从远处看大图像是你的目标图像,近处看这个图像其实是由小图像组成的。效果就是这个样子的,用自己的图镇楼!!!
2. 怎样生成蒙太奇马赛克图像?
要想生成蒙太奇马赛克图像你要明确两个部分:第一个就你的目标图像,也就是从远处看你想要生成的图像;第二个部分就是图像数据集,也就是你希望用哪些照片来生成你想要的图像,这个数据库一定要大,理论上是在数据库中找到和目标图像像素最相近的图像来代替图像中的像素值。我用的CIFAR100数据集,其包括5万训练图像和1万测试图像,我只采用了训练图像。
第一步:将CIFAR100数据的5万张训练图像全部放到一个文件夹下;代码如下:
importnumpy as np
from PIL import Image
import os
def unpickle(file):
import pickle
fo = open(file, 'rb')
dict = pickle.load(fo, encoding='latin1') #encoding='latin1'
fo.close()
return dict
def loadCifarBatch(filename, foldername):
dict = unpickle(filename)
# print(dict.keys())
# dict_keys(['filenames','batch_label', 'fine_labels', 'coarse_labels', 'data'])
batch_label = dict['batch_label']
fine_labels = dict['fine_labels']
coarse_labels = dict['coarse_labels']
batch_label = np.array(batch_label)
fine_labels = np.array(fine_labels)
coarse_labels =np.array(coarse_labels)
data = dict['data']
# print(data.shape())
if foldername == "train":
data = data.reshape(50000, 3, 32, 32)
elif foldername == "test":
data = data.reshape(10000, 3, 32, 32)
return data, batch_label, fine_labels, coarse_labels
def saveImage(filename, foldername):
imagedata, batch_label, fine_labels, coarse_labels = loadCifarBatch(filename, foldername)
label2classdict = unpickle('cifar-100-python/meta')
print(label2classdict.keys())
label2classfine = label2classdict['fine_label_names']
trainImgNum = 0
for i in range(imagedata.shape[0]):
print(i)
image = imagedata[i]
imgR, imgG, imgB = image[0], image[1], image[2]
imgR = Image.fromarray(imgR)
imgG = Image.fromarray(imgG)
imgB = Image.fromarray(imgB)
img = Image.merge("RGB", (imgR, imgG, imgB))
label = fine_labels[i]
classname = label2classfine[label]
if foldername == "train":
name = str(trainImgNum) + ".jpg"
# name = classname + "_" +str(trainImgNum) + ".png"
elif foldername == "test":
name = str(trainImgNum) + ".jpg"
# saveimgname = os.path.join(foldername,classname, name)
saveimgname = os.path.join("train", name)
print(saveimgname)
# savepath = os.path.join(foldername,classname)
savepath = foldername
if not os.path.exists(savepath):
os.makedirs(savepath)
img.save(saveimgname, "JPEG")
trainImgNum += 1
def main():
filename = 'cifar-100-python/train'
foldername = "train"
saveImage(filename, foldername)
if __name__ == "__main__":
main()
第二步,使用photomosaic包来实现我们的功能,如果没有安装,要先安装pip install photomosaic;
1)第一步要先判断自己的图像是否能够由整数个小图像组成,比如自己的图像是2399*1800*3,要先将自己的图像转换为2400*1800*3;
Code:
import cv2
img = cv2.imread("3.jpg")
print(img.shape)
res = cv2.resize(img, (2400, 1800))
cv2.imwrite("3_1.jpg", res)
2)开始生成自己的蒙太奇马赛克图像
import photomosaic as pm image = pm.imread("3_1.jpg") pool = pm.make_pool('train/*.jpg', sample_size=50000) mosaic = pm.basic_mosaic(image, pool, (480, 360)) pm.imsave('montage2.jpg', mosaic)
pm.make_pool函数中的第一参数指的是你数据库的路径,因为我的数据库中的每个图像是jpg格式,所以是*.Jpg
pm.basic_mosaic(image, pool, (480, 360)) 其中(480, 360)是指每一行和每一列使用数据库中的图像的个数。