DDCTF 拼图

第一次在ctf比赛中获得奖金,虽然奖金不多,但也想纪念纪念。

滴滴ctf拼图题,一开始为了尝试抢一血和队友手撸图片,最终也很幸运,真的解开了。也因为这个一血获得了200元。

上图是在6400片中用眼神看出的flag图片并用ps拼出来的心路历程。

以下附上自动拼图脚本

from PIL import Image
import imagehash
import os
import time

# 基础配置
# 后面一定要有反斜杠
source_path = r'C:\Users\34603\Desktop\临时\比赛题目andWP\DDCTF\\'
source_image = Image.open(r'C:\Users\34603\Desktop\临时\比赛题目andWP\DDCTF\demo.jpg')
dest_path = r'C:\Users\34603\Desktop\临时\比赛题目andWP\DDCTF\\'
chip_path = r'C:\Users\34603\Desktop\临时\比赛题目andWP\DDCTF\file_d0wnl0ad\\'
chip_width = 51
chip_height = 27

source_width = source_image.width
source_height = source_image.height
width_num = source_width // chip_width
height_num = source_height // chip_height

dha_dic = {}
aha_dic = {}
print("正在计算dhash和ahash")
chip_num = len(os.listdir(chip_path))
flag_dic = {}
for file in os.listdir(chip_path):
    temp_image = Image.open(chip_path + file)
    dha_dic[file] = imagehash.dhash(temp_image)
    aha_dic[file] = imagehash.average_hash(temp_image)
    flag_dic[file] = True

print("共" + str(len(aha_dic)) + "张图片")
print("正在匹配图片")
dest_image = Image.new('RGB', (source_width, source_height), '#FFFFFF')
count = 0
# try:
# 从左往右,按列比对
for i in range(width_num):
    for j in range(height_num):
        findflags = None
        box = (i * chip_width, j * chip_height, i * chip_width + chip_width, j * chip_height + chip_height)
        cop = source_image.crop(box)
        cop_dhash = imagehash.dhash(cop)
        cop_ahash = imagehash.average_hash(cop)
        # 先00限制死,
        for im in dha_dic:
            if (cop_dhash - dha_dic[im]) == 0:
                if (cop_ahash - aha_dic[im]) == 0:
                    # print(cop_dhash - dha_dic[im], i, j)
                    dest_image.paste(Image.open(chip_path + im), box)
                    flag_dic[im] = False
                    findflags = im
                    break
        # 如果00不行,那就11,
        if findflags is None:
            for im in dha_dic:
                if (cop_dhash - dha_dic[im]) <= 5:
                    if (cop_ahash - aha_dic[im]) <= 5:
                        dest_image.paste(Image.open(chip_path + im), box)
                        flag_dic[im] = False
                        findflags = im

        if findflags is not None:
            # 这里其实可以选择删不删除
            aha_dic.pop(findflags)
            dha_dic.pop(findflags)
    print("第" + str(i) + "列!")
# except:
#     pass

unfind_list = []
unfind_path = dest_path + time.strftime("%Y%m%d%H%M%S", time.localtime()) + "\\"
os.mkdir(unfind_path)

for i in flag_dic:
    if flag_dic[i]:
        temp_image = Image.open(chip_path + i).save(unfind_path + i)
        unfind_list.append(i)

print("完成,一共" + str(chip_num) + "个拼图")
print("有" + str(len(unfind_list)) + "未匹配成功")
print("已经保存在" + unfind_path + "文件夹")

dest_image.show()
dest_image.save(dest_path + 'result.png')

发表评论