Python——基于PIL和CV2实现自动拼图解决方案

解决方案 

# python3
import cv2
from PIL import Image
import numpy as np
import os
import shutil
import threading

# 读取目标图片
source = cv2.imread(r"C:/Users/Lenovo/Desktop/pt/source.jpg")
# 拼接结果
target = Image.fromarray(np.zeros(source.shape, np.uint8))
# 图库目录
dirs_path = r"C:/Users/Lenovo/Desktop/pt/pingTu"
# 差异图片存放目录
dst_path = r"C:/Users/Lenovo/Desktop/pt/new1"


def match(temp_file):
    # 读取模板图片
    template = cv2.imread(temp_file)
    # 获得模板图片的高宽尺寸
    theight, twidth = template.shape[:2]
    # 执行模板匹配,采用的匹配方式cv2.TM_SQDIFF_NORMED
    result = cv2.matchTemplate(source, template, cv2.TM_SQDIFF_NORMED)
    # 归一化处理
    cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX, -1)
    # 寻找矩阵(一维数组当做向量,用Mat定义)中的最大值和最小值的匹配结果及其位置
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    target.paste(Image.fromarray(template), min_loc)
    return abs(min_val)


class MThread (threading.Thread):
    def __init__(self, file_name):
        threading.Thread.__init__(self)
        self.file_name = file_name

    def run(self):
        real_path = os.path.join(dirs_path, k)
        rect = match(real_path)
        if rect > 1e-10:
            print(rect)
            shutil.copy(real_path, dst_path)


count = 0
dirs = os.listdir(dirs_path)
threads = []
for k in dirs:
    if k.endswith('jpg'):
        count += 1
        print("processing on pic"+str(count))
        mt = MThread(k)
        mt.start()
        threads.append(mt)
    else:
        continue
# 等待所有线程完成
for t in threads:
    t.join()
target.show()
target.save(r"C:/Users/Lenovo/Desktop/pt/target.jpg")


参考文章

第十一届极客大挑战部分WP(无re和pwn)

从DDCTF2020-拼图题,学习如何做拼图题

Python实现将一张图片放到另一张图片指定的位置上并合成一张图

Python3 多线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Starzkg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值