comic-hasher/cmd/hash.py

70 lines
1.8 KiB
Python
Raw Normal View History

from __future__ import annotations
import argparse
import pathlib
import sys
from typing import Collection
from typing import Sequence
import imagehash
import numpy
2024-05-10 13:58:04 -07:00
from PIL import Image
ap = argparse.ArgumentParser()
ap.add_argument('--file', type=pathlib.Path)
ap.add_argument('--debug', action='store_true')
2024-05-10 13:58:04 -07:00
opts = ap.parse_args()
opts.file = pathlib.Path(opts.file)
hash_size = 8
image = Image.open(opts.file)
gray = image.copy().convert('L')
resized = gray.copy().resize((hash_size, hash_size), Image.Resampling.LANCZOS)
def print_image(image: Image.Image) -> None:
for row in numpy.asarray(image):
2024-08-04 18:12:00 -07:00
print('[ ', end='', file=sys.stderr)
2024-05-10 13:58:04 -07:00
for i in row:
if isinstance(i, Collection):
2024-08-04 18:12:00 -07:00
print('{ ', end='', file=sys.stderr)
2024-05-10 13:58:04 -07:00
for idx, x in enumerate(i):
if idx == len(i) - 1:
2024-08-04 18:12:00 -07:00
print(f'{int(x):03d} ', end='', file=sys.stderr)
2024-05-10 13:58:04 -07:00
else:
2024-08-04 18:12:00 -07:00
print(f'{int(x):03d}, ', end='', file=sys.stderr)
print('}, ', end='', file=sys.stderr)
2024-05-10 13:58:04 -07:00
else:
2024-08-04 18:12:00 -07:00
print(f'{int(i):03d}, ', end='', file=sys.stderr)
print(']', file=sys.stderr)
2024-05-10 13:58:04 -07:00
2024-05-10 13:58:04 -07:00
def bin_str(hash):
return ''.join(str(b) for b in 1 * hash.hash.flatten())
2024-08-04 18:12:00 -07:00
if opts.debug:
image.save('py.rgb.png')
print('rgb', file=sys.stderr)
2024-08-04 18:12:00 -07:00
print_image(image)
print(file=sys.stderr)
2024-05-10 13:58:04 -07:00
2024-08-04 18:12:00 -07:00
if opts.debug:
gray.save('py.gray.png')
print('gray', file=sys.stderr)
2024-08-04 18:12:00 -07:00
print_image(gray)
print(file=sys.stderr)
2024-05-10 13:58:04 -07:00
2024-08-04 18:12:00 -07:00
if opts.debug:
resized.save('py.resized.png')
print('resized', file=sys.stderr)
2024-08-04 18:12:00 -07:00
print_image(resized)
print(file=sys.stderr)
2024-05-10 13:58:04 -07:00
print('ahash: ', str(imagehash.average_hash(image)))
print('dhash: ', str(imagehash.dhash(image)))
print('phash: ', str(imagehash.phash(image)))