85 lines
2.1 KiB
Python
85 lines
2.1 KiB
Python
|
from PIL import Image
|
||
|
import math
|
||
|
import argparse
|
||
|
import os.path
|
||
|
|
||
|
parser = argparse.ArgumentParser(
|
||
|
prog = 'Image Edit Script',
|
||
|
description = 'Manipulate or extract information from an image file',
|
||
|
epilog = '')
|
||
|
|
||
|
parser.add_argument('filename') # positional argument
|
||
|
parser.add_argument('-n', '--bytesperline')
|
||
|
parser.add_argument('-b', '--lsbfirst', action='store_true')
|
||
|
parser.add_argument('-i', '--invert', action='store_true')
|
||
|
|
||
|
args = parser.parse_args()
|
||
|
|
||
|
lsbfirst=args.lsbfirst
|
||
|
invert=args.invert
|
||
|
|
||
|
bytesperline=16
|
||
|
if args.bytesperline is not None:
|
||
|
bytesperline=args.bytesperline #for output formatting
|
||
|
|
||
|
|
||
|
im = Image.open(args.filename) # Can be many different formats.
|
||
|
pix = im.load()
|
||
|
print(im.size) # Get the width and hight of the image for iterating over
|
||
|
|
||
|
|
||
|
array=[] #array with every element a byte
|
||
|
|
||
|
thresh=128 #threshold brightness
|
||
|
|
||
|
def calculateDistance(x1,y1,x2,y2):
|
||
|
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
|
||
|
return dist
|
||
|
|
||
|
temp_byte=0
|
||
|
temp_byte_pos=0
|
||
|
for y in range(im.size[1]):
|
||
|
for x in range(im.size[0]):
|
||
|
c = pix[x,y] #get pixel
|
||
|
r=c[0]
|
||
|
g=c[1]
|
||
|
b=c[2]
|
||
|
if invert:
|
||
|
r=255-r
|
||
|
g=255-g
|
||
|
b=255-b
|
||
|
|
||
|
if ((r+g+b)/3 < thresh ): #black
|
||
|
if lsbfirst:
|
||
|
temp_byte+=1<<temp_byte_pos
|
||
|
else:
|
||
|
temp_byte+=1<<(7-temp_byte_pos)
|
||
|
|
||
|
temp_byte_pos+=1
|
||
|
if temp_byte_pos>=8: #finished assemblying byte
|
||
|
array.append(temp_byte)
|
||
|
temp_byte_pos=0 #reset
|
||
|
temp_byte=0
|
||
|
|
||
|
|
||
|
if os.path.isfile(args.filename+'.txt'):
|
||
|
print("Outputfile "+args.filename+".txt exists")
|
||
|
exit()
|
||
|
|
||
|
with open(args.filename+'.txt', 'w') as f:
|
||
|
f.write("const unsigned char gImage_4in2[] = {")
|
||
|
f.write('\r\n')
|
||
|
counter=0
|
||
|
for a in array: #for every byte
|
||
|
f.write("0X{:02X}".format(a)+',') #Example output: 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,
|
||
|
counter+=1
|
||
|
if counter>=bytesperline:
|
||
|
f.write('\r\n')
|
||
|
counter=0
|
||
|
f.write("};")
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|