Created
January 4, 2020 13:07
-
-
Save ymt117/940b084460caa4e956bb07b3500c9f8c to your computer and use it in GitHub Desktop.
画像をcsvファイルに,csvファイルを画像に変換するプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import sys | |
import csv | |
import argparse | |
ap = argparse.ArgumentParser() | |
ap.add_argument('-e', help='path to encode image file') | |
ap.add_argument('-d', help='path to decode csv file') | |
args = ap.parse_args() | |
def encode_csv(filename): | |
# 画像を読み込む | |
with Image.open(filename) as img: | |
# グレースケールに変換 | |
img_gray = img.convert('L') | |
width, height = img_gray.size | |
for h in range(0, height): | |
l = [] | |
for w in range(0, width): | |
l.append(img_gray.getpixel((w, h))) | |
# csvファイルにピクセル値を書き込む | |
with open('secret.csv', 'a', newline='') as f: | |
csv.writer(f).writerow(l) | |
def decode_csv(filename): | |
# csvファイルを読み込む | |
with open(filename) as f: | |
reader = csv.reader(f) | |
l = [row for row in reader] | |
# リストを転置 | |
l_t = [list(x) for x in zip(*l)] | |
w = int(len(l[0])) | |
h = int(len(l)) | |
size = (w, h) | |
img = Image.new('L', size) | |
for x in range(0, w): | |
for y in range(0, h): | |
#print(x, end="\t") | |
#print(y) | |
img.putpixel((x, y), int(l_t[x][y])) | |
img.save('decoded_img.png') | |
''' | |
Main program | |
''' | |
if args.e is not None: | |
encode_csv(args.e) | |
elif args.d is not None: | |
decode_csv(args.d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment