python实现马赛克拼图!

博客分享了如何使用Python实现马赛克拼图的代码,强调需在终端运行命令`python mosaic_v2.py -i "D:imagepic.jpg" -t "D:image"`。博主鼓励对编程感兴趣的人学习Python,并推荐了一个Python学习交流群。
摘要由CSDN通过智能技术生成

直接上代码!

代码如下:

#!/usr/local/bin/python3
#  --*-- coding:utf8 --*--

import getopt
import sys
import os

import logging
from PIL import Image
from multiprocessing import Process, Queue, cpu_count

TILE_SIZE = 30  # 素材图片大小
TILE_MATCH_RES = 10  #配置指数  ,值越大匹配度越高,执行时间越长
ENLARGEMENT = 4  # 生成的图片是原始图片的多少倍

TILE_BLOCK_SIZE = int(TILE_SIZE / max(min(TILE_MATCH_RES, TILE_SIZE), 1))
WORKER_COUNT = max(cpu_count() - 1, 1)
EOQ_VALUE = None
WARN_INFO = """ *缺少有效参数*
    参数:
        -i [--image]     : 原图片地址
        -t [--tiles_dir] : 素材目录地址
        -o [--outfile]   : 输出文件地址 【可选】
"""


class TileProcessor:
    def __init__(self, tiles_directory):
        self.tiles_directory = tiles_directory

    def __process_tile(self, tile_path):
        try:
            img = Image.open(tile_path)
            # tiles must be square, so get the largest square that fits inside the image
            w = img.size[0]
            h = img.size[1]
            min_dimension = min(w, h)
            w_crop = (w - min_dimension) / 2
            h_crop = (h - min_dimension) / 2
            img = img.crop((w_crop, h_crop, w - w_crop, h - h_crop))
            large_tile_img = img.resize((TILE_SIZE, TILE_SIZE), Image.ANTIALIAS)
            small_tile_img = img.resize((int(TILE_SIZE / TILE_BLOCK_SIZE), int(TILE_SIZE / TILE_BLOCK_SIZE)),
                                        Image.ANTIALIAS)
            return (large_tile_img.convert('RGB'), small_tile_img.convert('RGB'))
        except Exception as e:
            logging.warning(e)
            return (None, None)

    def get_tiles(self):
        large_tiles = []
        small_tiles = []

        logging.info('从 \'%s\' 获取图片素材...' % self.tiles_directory)

        # search the tiles directory recursively
        for root, subFolders, files in os.walk(self.tiles_directory):
            for tile_name in files:
                tile_path = os.path.join(root, tile_name)
                large_tile, small_tile = self.__process_tile(tile_path)
                logging.debug(large_tile)
                logging.d
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值