温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么生成一个马赛克画

发布时间:2021-07-10 11:19:41 来源:亿速云 阅读:135 作者:Leah 栏目:大数据

这篇文章将为大家详细讲解有关Python中怎么生成一个马赛克画,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

import re
import os
import cv2
import numpy as np
from tqdm import tqdm

IMG_DIR = "images"

def load_all_images(tile_row, tile_col):
   img_dir = IMG_DIR
   filenames = os.listdir(img_dir)
   result = []
   print(len(filenames))
   for filename in tqdm(filenames):
       if not re.search(".jpg", filename, re.I):
           continue
       try:
           filepath = os.path.join(img_dir, filename)
           im = cv2.imread(filepath)
           row = im.shape[0]
           col = im.shape[1]
           im = resize(im, tile_row, tile_col)
           result.append(np.array(im))
       except Exception as e:
           msg = "error with {} - {}".format(filepath, str(e))
           print(msg)
   return np.array(result, dtype=np.uint8)

这里load_all_images函数的参数就是统一后的尺寸,tile_row和tile_col分别对应高和宽。

下面的代码对要转换的图片进行分割

img = cv2.imread(infile)
tile_row, tile_col = get_tile_row_col(img.shape)
for row in range(0, img_shape[0], tile_row):
   for col in range(0, img_shape[1], tile_col):
       roi = img[row:row+tile_row,col:col+tile_col,:]

我们将要转换的图片分割成一个个小方格,tile_row和tile_col是小方格的高和宽,roi存取小方格中的图片数据。

下面是计算两张图片相似度的函数

from scipy.spatial.distance import euclidean
def img_distance(im1, im2):
   if im1.shape != im2.shape:
       msg = "shapes are different {} {}".format(im1.shape, im2.shape)
       raise Exception(msg)
   array1 = im1.flatten()
   array2 = im2.flatten()
   dist = euclidean(array1, array2)
   return dist

im1和im2是两张图片的数据,图片数据是一个三维的numpy数组,这里我们将三维数组转换成一维数组后,比较两者的欧式距离。之后要找出最相似的图片,只需遍历图片集中所有的图片,找到距离最短的那张图片,去替换原图中的小方格就可以了。

关于Python中怎么生成一个马赛克画就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI