Skip to content

Instantly share code, notes, and snippets.

@ymt117
Last active January 20, 2020 05:39
Show Gist options
  • Save ymt117/d084b3ac41f07d17337f31fe4e424c8a to your computer and use it in GitHub Desktop.
Save ymt117/d084b3ac41f07d17337f31fe4e424c8a to your computer and use it in GitHub Desktop.
カバー画像の各ピクセル下位ビット4桁にシークレット画像の各ピクセル上位ビット4桁を隠す
from PIL import Image
import sys
import csv
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-c', help='path to cover image file')
ap.add_argument('-s', help='path to secret image file')
ap.add_argument('-d', help='path to decode image file')
args = ap.parse_args()
def secret_image_resize(img_cov, img_sec):
w_cov, h_cov = img_cov.size
w_sec, h_sec = img_sec.size
if w_cov < w_sec or h_cov < h_sec: #cover fileよりsecret fileのピクセルサイズが大きい
# secret fileの縦横大きいほうをcover fileに揃える
if w_sec > h_sec: # 横が大きいとき
re_h = w_cov / w_sec * h_sec
img_sec = img_sec.resize((int(w_cov), int(re_h)))
else: # 縦が大きいとき
re_w = h_cov / h_sec * w_sec
img_sec = img_sec.resize((int(re_w), int(h_cov)))
return img_sec
def encode_csv(cover_file, secret_file):
# 画像を読み込む
with Image.open(cover_file) as img_cov:
with Image.open(secret_file) as img_sec:
# cover fileよりsecret fileのピクセルサイズが大きい場合,secret fileをリサイズする
img_sec = secret_image_resize(img_cov, img_sec)
w_cov, h_cov = img_cov.size
w_sec, h_sec = img_sec.size
size = (w_cov, h_cov)
img_out = Image.new('RGB', size)
for h in range(0, h_cov):
for w in range(0, w_cov):
if h >= h_sec or w >= w_sec:
pixel_cov = list(img_cov.getpixel((w, h)))
for i in range(0, 3):
pixel_cov[i] = (pixel_cov[i] >> 4) << 4
img_out.putpixel((w, h), tuple(pixel_cov))
else:
pixel_cov = list(img_cov.getpixel((w, h)))
pixel_sec = list(img_sec.getpixel((w, h)))
for i in range(0, 3):
# R,G,Bの各ピクセルにおいて,下位ビット4つをsecret fileの上位ビット4つと置き換える
pixel_cov[i] = ((pixel_cov[i] >> 4) << 4) | (pixel_sec[i] >> 4)
img_out.putpixel((w, h), tuple(pixel_cov))
img_out.save('output.png', 'PNG')
def decode_csv(filename):
# 画像を読み込む
with Image.open(filename) as img:
width, height = img.size
size = (width, height)
img_out = Image.new('RGB', size)
for h in range(0, height):
for w in range(0, width):
pixel = list(img.getpixel((w, h)))
for i in range(0, 3):
# 下位ビットの画像を抽出する
# R,G,Bの各ピクセルにおいて,下位ビットを取り出し,左に4ビットシフトする
pixel[i] = (pixel[i] & 0b00001111) << 4
img_out.putpixel((w, h), tuple(pixel))
img_out.save('decoded_img.png')
'''
Main program
'''
if args.c is not None and args.s is not None:
encode_csv(args.c, args.s)
elif args.d is not None:
decode_csv(args.d)
else:
print("Error!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment