Include other image hashes
It would be very helpful if the database could also include some other commonly used image hashes.
people can use them to perform joint analysis
import imagehash
...
imagehash.phash(img)
imagehash.dhash(img)
imagehash.whash(img)
imagehash.average_hash(img)
there are many image hash algorithms I want to add (like edge histogram, FCTH, JCD, CEDD, etc) but I've limited resources and budget.
which one(s) do you think would be most useful?
Based on my tests, phash is good for similarity search. One can further verify dhash and whash to perform exact match. This configuration will lead to zero collision (in my tests) using in total 8*3 bytes of binary stored in the database.
All of them are using the [default parameter](https://github.com/JohannesBuchner/imagehash] (hashsize=8, which is 20 characters including 0x if showed on display), which most existing code uses.
I try to put together a typescript for you. please use it freely. but please test it against the original python library before using it.
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/**
* TypeScript port of https://github.com/JohannesBuchner/imagehash/blob/master/imagehash/__init__.py
*
* Notes:
* - Function names, parameter names, defaults, and high-level behavior are kept the same.
* - This includes TypeScript implementations for:
* - convert('L')
* - DCT
* - wavedec2 / waverec2
* - `ANTIALIAS` is represented by bilinear resize here.
*
* Image input:
* - This port uses a lightweight `ImageLike` interface with `.convert('L')`, `.resize()`, and `.size`.
* - `RawImage` below can wrap RGBA/RGB/gray pixel data.
*/
type NDArray = boolean[][];
const ANTIALIAS = "ANTIALIAS" as const;
type ResampleFilter = typeof ANTIALIAS;
type WhashMode = "haar" | "db4";
interface ImageLike {
readonly size: [number, number]; // [width, height]
convert(mode: "L"): GrayImage;
resize(size: [number, number], filter?: ResampleFilter): GrayImage;
}
class GrayImage implements ImageLike {
public readonly width: number;
public readonly height: number;
public readonly data: Float64Array; // row-major grayscale [0..255]
constructor(width: number, height: number, data: ArrayLike<number>) {
if (data.length !== width * height) {
throw new Error("GrayImage data length does not match width * height");
}
this.width = width;
this.height = height;
this.data = Float64Array.from(data);
}
get size(): [number, number] {
return [this.width, this.height];
}
convert(mode: "L"): GrayImage {
if (mode !== "L") {
throw new Error(`Unsupported mode: ${mode}`);
}
return new GrayImage(this.width, this.height, this.data);
}
resize(size: [number, number], _filter: ResampleFilter = ANTIALIAS): GrayImage {
const [newWidth, newHeight] = size;
const out = resizeBilinearGray(this.data, this.width, this.height, newWidth, newHeight);
return new GrayImage(newWidth, newHeight, out);
}
to2DArray(): number[][] {
const out: number[][] = [];
for (let y = 0; y < this.height; y++) {
const row: number[] = [];
for (let x = 0; x < this.width; x++) {
row.push(this.data[y * this.width + x]);
}
out.push(row);
}
return out;
}
static from2DArray(arr: number[][]): GrayImage {
const height = arr.length;
const width = height > 0 ? arr[0].length : 0;
const data = new Float64Array(width * height);
for (let y = 0; y < height; y++) {
if (arr[y].length !== width) {
throw new Error("Jagged 2D array is not supported");
}
for (let x = 0; x < width; x++) {
data[y * width + x] = arr[y][x];
}
}
return new GrayImage(width, height, data);
}
}
/**
* Wrapper for RGB/RGBA/Gray source pixels.
* This gives you convert('L') like PIL.
*/
class RawImage implements ImageLike {
public readonly width: number;
public readonly height: number;
public readonly channels: 1 | 3 | 4;
public readonly data: Uint8ClampedArray | Uint8Array | Float64Array;
constructor(
width: number,
height: number,
data: ArrayLike<number>,
channels: 1 | 3 | 4
) {
if (data.length !== width * height * channels) {
throw new Error("RawImage data length does not match width * height * channels");
}
this.width = width;
this.height = height;
this.channels = channels;
this.data = Float64Array.from(data);
}
get size(): [number, number] {
return [this.width, this.height];
}
convert(mode: "L"): GrayImage {
if (mode !== "L") {
throw new Error(`Unsupported mode: ${mode}`);
}
const out = new Float64Array(this.width * this.height);
if (this.channels === 1) {
for (let i = 0; i < out.length; i++) out[i] = Number(this.data[i]);
return new GrayImage(this.width, this.height, out);
}
if (this.channels === 3) {
for (let i = 0, j = 0; i < out.length; i++, j += 3) {
const r = Number(this.data[j + 0]);
const g = Number(this.data[j + 1]);
const b = Number(this.data[j + 2]);
// PIL-like luminance conversion
out[i] = clamp255(0.299 * r + 0.587 * g + 0.114 * b);
}
return new GrayImage(this.width, this.height, out);
}
// RGBA
for (let i = 0, j = 0; i < out.length; i++, j += 4) {
const r = Number(this.data[j + 0]);
const g = Number(this.data[j + 1]);
const b = Number(this.data[j + 2]);
// Alpha is ignored here, matching common convert('L') behavior over composite-free pixel values
out[i] = clamp255(0.299 * r + 0.587 * g + 0.114 * b);
}
return new GrayImage(this.width, this.height, out);
}
resize(size: [number, number], filter: ResampleFilter = ANTIALIAS): GrayImage {
return this.convert("L").resize(size, filter);
}
}
class ImageHash {
/**
* Hash encapsulation. Can be used for dictionary keys and comparisons.
*/
public hash: NDArray;
constructor(binary_array: NDArray) {
this.hash = binary_array;
}
toString(): string {
return _binary_array_to_hex(flattenBoolean2D(this.hash));
}
inspect(): string {
return JSON.stringify(this.hash);
}
sub(other: ImageHash | null): number {
if (other === null) {
throw new TypeError("Other hash must not be None.");
}
const a = flattenBoolean2D(this.hash);
const b = flattenBoolean2D(other.hash);
if (a.length !== b.length) {
throw new TypeError(
`ImageHashes must be of the same shape. ${JSON.stringify(shapeOf(this.hash))} ${JSON.stringify(shapeOf(other.hash))}`
);
}
let count = 0;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) count++;
}
return count;
}
equals(other: unknown): boolean {
if (other === null || other === undefined) {
return false;
}
if (!(other instanceof ImageHash)) {
return false;
}
const a = flattenBoolean2D(this.hash);
const b = flattenBoolean2D(other.hash);
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
notEquals(other: unknown): boolean {
if (other === null || other === undefined) {
return false;
}
return !this.equals(other);
}
hashCode(): number {
// this returns a 8 bit integer, intentionally shortening the information
const flat = flattenBoolean2D(this.hash);
let s = 0;
for (let i = 0; i < flat.length; i++) {
if (flat[i]) s += 2 ** (i % 8);
}
return s;
}
len(): number {
// Returns the bit length of the hash
const [rows, cols] = shapeOf(this.hash);
return rows * cols;
}
}
export function phash(image: ImageLike, hash_size = 8, highfreq_factor = 4): ImageHash {
/**
* Perceptual Hash computation.
*
* Implementation follows
* https://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
*
* @image must be a PIL instance (ported here to ImageLike).
*/
if (hash_size < 2) {
throw new ValueError("Hash size must be greater than or equal to 2");
}
const img_size = hash_size * highfreq_factor;
image = image.convert("L").resize([img_size, img_size], ANTIALIAS);
const pixels = (image as GrayImage).to2DArray();
const dct0 = dct2D(pixels, 0);
const dctlowfreq = slice2D(dct0, 0, hash_size, 0, hash_size);
const med = median2D(dctlowfreq);
const diff = map2DBool(dctlowfreq, (v) => v > med);
return new ImageHash(diff);
}
export function dhash(image: ImageLike, hash_size = 8): ImageHash {
/**
* Difference Hash computation.
*
* following https://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html
*
* computes differences horizontally
*
* @image must be a PIL instance.
*/
// resize(w, h), but numpy.array((h, w))
if (hash_size < 2) {
throw new ValueError("Hash size must be greater than or equal to 2");
}
image = image.convert("L").resize([hash_size + 1, hash_size], ANTIALIAS);
const pixels = (image as GrayImage).to2DArray();
const diff: boolean[][] = [];
for (let y = 0; y < pixels.length; y++) {
const row: boolean[] = [];
for (let x = 1; x < pixels[y].length; x++) {
row.push(pixels[y][x] > pixels[y][x - 1]);
}
diff.push(row);
}
return new ImageHash(diff);
}
export function whash(
image: ImageLike,
hash_size = 8,
image_scale: number | null = null,
mode: WhashMode = "haar",
remove_max_haar_ll = true
): ImageHash {
/**
* Wavelet Hash computation.
*
* based on https://www.kaggle.com/c/avito-duplicate-ads-detection/
*
* @image must be a PIL instance.
* @hash_size must be a power of 2 and less than @image_scale.
* @image_scale must be power of 2 and less than image size. By default is equal to max
* power of 2 for an input image.
* @mode :
* 'haar' - Haar wavelets, by default
* 'db4' - Daubechies wavelets
* @remove_max_haar_ll - remove the lowest low level (LL) frequency using Haar wavelet.
*/
if (image_scale !== null) {
assert((image_scale & (image_scale - 1)) === 0, "image_scale is not power of 2");
} else {
const image_natural_scale = 2 ** Math.floor(Math.log2(Math.min(...image.size)));
image_scale = Math.max(image_natural_scale, hash_size);
}
const ll_max_level = Math.floor(Math.log2(image_scale));
const level = Math.floor(Math.log2(hash_size));
assert((hash_size & (hash_size - 1)) === 0, "hash_size is not power of 2");
assert(level <= ll_max_level, "hash_size in a wrong range");
const dwt_level = ll_max_level - level;
image = image.convert("L").resize([image_scale, image_scale], ANTIALIAS);
let pixels = divide2D((image as GrayImage).to2DArray(), 255.0);
// Remove low level frequency LL(max_ll) if @remove_max_haar_ll using haar filter
if (remove_max_haar_ll) {
let coeffs = wavedec2(pixels, "haar", ll_max_level);
coeffs = coeffs.slice() as WaveCoeffs;
coeffs[0] = zerosLike2D(coeffs[0] as number[][]);
pixels = waverec2(coeffs, "haar");
}
// Use LL(K) as freq, where K is log2(@hash_size)
const coeffs = wavedec2(pixels, mode, dwt_level);
const dwt_low = coeffs[0] as number[][];
// Subtract median and compute hash
const med = median2D(dwt_low);
const diff = map2DBool(dwt_low, (v) => v > med);
return new ImageHash(diff);
}
/* =========================
* convert('L') / resize
* ========================= */
function resizeBilinearGray(
src: Float64Array,
srcW: number,
srcH: number,
dstW: number,
dstH: number
): Float64Array {
const out = new Float64Array(dstW * dstH);
if (dstW === 0 || dstH === 0) return out;
const xScale = srcW / dstW;
const yScale = srcH / dstH;
for (let y = 0; y < dstH; y++) {
const sy = (y + 0.5) * yScale - 0.5;
const y0 = clampInt(Math.floor(sy), 0, srcH - 1);
const y1 = clampInt(y0 + 1, 0, srcH - 1);
const wy = sy - y0;
for (let x = 0; x < dstW; x++) {
const sx = (x + 0.5) * xScale - 0.5;
const x0 = clampInt(Math.floor(sx), 0, srcW - 1);
const x1 = clampInt(x0 + 1, 0, srcW - 1);
const wx = sx - x0;
const p00 = src[y0 * srcW + x0];
const p01 = src[y0 * srcW + x1];
const p10 = src[y1 * srcW + x0];
const p11 = src[y1 * srcW + x1];
const top = p00 * (1 - wx) + p01 * wx;
const bottom = p10 * (1 - wx) + p11 * wx;
out[y * dstW + x] = top * (1 - wy) + bottom * wy;
}
}
return out;
}
/* =========================
* DCT
* ========================= */
/**
* scipy.fftpack.dct(x, axis=?, type=2, norm=None)-style DCT.
* This is DCT-II with no normalization.
*/
export function dct1D(x: number[]): number[] {
const N = x.length;
const out = new Array<number>(N);
for (let k = 0; k < N; k++) {
let sum = 0;
for (let n = 0; n < N; n++) {
sum += x[n] * Math.cos((Math.PI * k * (2 * n + 1)) / (2 * N));
}
out[k] = 2 * sum;
}
return out;
}
/**
* dct(matrix, axis=0 or 1)
*/
export function dct2D(matrix: number[][], axis: 0 | 1 = 0): number[][] {
const h = matrix.length;
const w = h > 0 ? matrix[0].length : 0;
const out = zeros2D(h, w);
if (axis === 0) {
for (let x = 0; x < w; x++) {
const col = new Array<number>(h);
for (let y = 0; y < h; y++) col[y] = matrix[y][x];
const d = dct1D(col);
for (let y = 0; y < h; y++) out[y][x] = d[y];
}
} else {
for (let y = 0; y < h; y++) {
out[y] = dct1D(matrix[y]);
}
}
return out;
}
/* =========================
* wavedec2 / waverec2
* ========================= */
type DetailCoeffs = [number[][], number[][], number[][]]; // [cH, cV, cD]
type WaveCoeffs = [number[][], ...DetailCoeffs[]];
/**
* Minimal pywt-like wavedec2.
*
* Return shape:
* [cA_n, (cH_n, cV_n, cD_n), ..., (cH_1, cV_1, cD_1)]
*
* This implementation supports:
* - haar
* - db4
*
* Boundary handling uses symmetric extension.
*/
export function wavedec2(
pixels: number[][],
mode: WhashMode,
level: number
): WaveCoeffs {
if (level < 0) throw new Error("level must be >= 0");
const coeffs: DetailCoeffs[] = [];
let current = clone2D(pixels);
const [loD, hiD, loR, hiR] = getWaveletFilters(mode);
for (let i = 0; i < level; i++) {
const { cA, cH, cV, cD } = dwt2(current, loD, hiD);
coeffs.push([cH, cV, cD]);
current = cA;
}
coeffs.reverse();
return [current, ...coeffs];
}
export function waverec2(coeffs: WaveCoeffs, mode: WhashMode): number[][] {
let current = clone2D(coeffs[0]);
const [, , loR, hiR] = getWaveletFilters(mode);
for (let i = 1; i < coeffs.length; i++) {
const [cH, cV, cD] = coeffs[i];
current = idwt2(current, cH, cV, cD, loR, hiR);
}
return current;
}
function dwt2(
input: number[][],
lo: number[],
hi: number[]
): { cA: number[][]; cH: number[][]; cV: number[][]; cD: number[][] } {
const h = input.length;
const w = h > 0 ? input[0].length : 0;
// rows
const lowRows: number[][] = [];
const highRows: number[][] = [];
for (let y = 0; y < h; y++) {
const { low, high } = dwt1D(input[y], lo, hi);
lowRows.push(low);
highRows.push(high);
}
const w2 = lowRows[0]?.length ?? 0;
// columns on lowRows -> cA, cV
const cA = zeros2D(Math.ceil(h / 2), w2);
const cV = zeros2D(Math.ceil(h / 2), w2);
for (let x = 0; x < w2; x++) {
const col = new Array<number>(h);
for (let y = 0; y < h; y++) col[y] = lowRows[y][x];
const { low, high } = dwt1D(col, lo, hi);
for (let y = 0; y < low.length; y++) cA[y][x] = low[y];
for (let y = 0; y < high.length; y++) cV[y][x] = high[y];
}
// columns on highRows -> cH, cD
const cH = zeros2D(Math.ceil(h / 2), w2);
const cD = zeros2D(Math.ceil(h / 2), w2);
for (let x = 0; x < w2; x++) {
const col = new Array<number>(h);
for (let y = 0; y < h; y++) col[y] = highRows[y][x];
const { low, high } = dwt1D(col, lo, hi);
for (let y = 0; y < low.length; y++) cH[y][x] = low[y];
for (let y = 0; y < high.length; y++) cD[y][x] = high[y];
}
return { cA, cH, cV, cD };
}
function idwt2(
cA: number[][],
cH: number[][],
cV: number[][],
cD: number[][],
loR: number[],
hiR: number[]
): number[][] {
const h2 = cA.length;
const w2 = h2 > 0 ? cA[0].length : 0;
const lowRows = zeros2D(h2 * 2, w2);
const highRows = zeros2D(h2 * 2, w2);
// reconstruct columns first
for (let x = 0; x < w2; x++) {
const aCol = new Array<number>(h2);
const vCol = new Array<number>(h2);
const hCol = new Array<number>(h2);
const dCol = new Array<number>(h2);
for (let y = 0; y < h2; y++) {
aCol[y] = cA[y][x];
vCol[y] = cV[y][x];
hCol[y] = cH[y][x];
dCol[y] = cD[y][x];
}
const lowRecon = idwt1D(aCol, vCol, loR, hiR);
const highRecon = idwt1D(hCol, dCol, loR, hiR);
for (let y = 0; y < lowRecon.length; y++) {
lowRows[y][x] = lowRecon[y];
highRows[y][x] = highRecon[y];
}
}
const out = zeros2D(h2 * 2, w2 * 2);
for (let y = 0; y < out.length; y++) {
out[y] = idwt1D(lowRows[y], highRows[y], loR, hiR);
}
return out;
}
function dwt1D(signal: number[], lo: number[], hi: number[]): { low: number[]; high: number[] } {
const outLen = Math.ceil(signal.length / 2);
const low = new Array<number>(outLen).fill(0);
const high = new Array<number>(outLen).fill(0);
for (let i = 0; i < outLen; i++) {
let sl = 0;
let sh = 0;
const base = 2 * i;
for (let k = 0; k < lo.length; k++) {
const idx = reflectIndex(base + k - Math.floor(lo.length / 2), signal.length);
sl += lo[k] * signal[idx];
sh += hi[k] * signal[idx];
}
low[i] = sl;
high[i] = sh;
}
return { low, high };
}
function idwt1D(low: number[], high: number[], loR: number[], hiR: number[]): number[] {
const outLen = low.length * 2;
const out = new Array<number>(outLen).fill(0);
for (let i = 0; i < low.length; i++) {
const base = 2 * i;
for (let k = 0; k < loR.length; k++) {
const idx = reflectIndex(base + k - Math.floor(loR.length / 2), outLen);
out[idx] += loR[k] * low[i];
out[idx] += hiR[k] * high[i];
}
}
return out;
}
function getWaveletFilters(mode: WhashMode): [number[], number[], number[], number[]] {
if (mode === "haar") {
const s = 1 / Math.sqrt(2);
const decLo = [s, s];
const decHi = [-s, s];
const recLo = [s, s];
const recHi = [s, -s];
return [decLo, decHi, recLo, recHi];
}
if (mode === "db4") {
// Daubechies 4 (db4) filter coefficients
const decLo = [
-0.010597401785069032,
0.0328830116668852,
0.030841381835560764,
-0.18703481171909308,
-0.027983769416859854,
0.6308807679298587,
0.7148465705529157,
0.2303778133088965,
];
const decHi = [
-0.2303778133088965,
0.7148465705529157,
-0.6308807679298587,
-0.027983769416859854,
0.18703481171909308,
0.030841381835560764,
-0.0328830116668852,
-0.010597401785069032,
];
const recLo = [
0.2303778133088965,
0.7148465705529157,
0.6308807679298587,
-0.027983769416859854,
-0.18703481171909308,
0.030841381835560764,
0.0328830116668852,
-0.010597401785069032,
];
const recHi = [
-0.010597401785069032,
-0.0328830116668852,
0.030841381835560764,
0.18703481171909308,
-0.027983769416859854,
-0.6308807679298587,
0.7148465705529157,
-0.2303778133088965,
];
return [decLo, decHi, recLo, recHi];
}
throw new Error(`Unsupported wavelet mode: ${mode}`);
}
/* =========================
* Helpers
* ========================= */
class ValueError extends Error {
constructor(message: string) {
super(message);
this.name = "ValueError";
}
}
function assert(condition: boolean, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function shapeOf(a: boolean[][]): [number, number] {
return [a.length, a.length ? a[0].length : 0];
}
function flattenBoolean2D(a: boolean[][]): boolean[] {
const out: boolean[] = [];
for (const row of a) {
for (const v of row) out.push(v);
}
return out;
}
function _binary_array_to_hex(bits: boolean[]): string {
if (bits.length === 0) return "";
const paddedLength = Math.ceil(bits.length / 4) * 4;
const padded = bits.slice();
while (padded.length < paddedLength) padded.push(false);
let hex = "";
for (let i = 0; i < padded.length; i += 4) {
let value = 0;
if (padded[i]) value += 8;
if (padded[i + 1]) value += 4;
if (padded[i + 2]) value += 2;
if (padded[i + 3]) value += 1;
hex += value.toString(16);
}
return hex;
}
function clamp255(v: number): number {
return Math.max(0, Math.min(255, v));
}
function clampInt(v: number, lo: number, hi: number): number {
return Math.max(lo, Math.min(hi, v));
}
function reflectIndex(i: number, len: number): number {
if (len <= 1) return 0;
while (i < 0 || i >= len) {
if (i < 0) i = -i - 1;
if (i >= len) i = 2 * len - i - 1;
}
return i;
}
function zeros2D(h: number, w: number): number[][] {
const out: number[][] = new Array(h);
for (let y = 0; y < h; y++) out[y] = new Array(w).fill(0);
return out;
}
function zerosLike2D(a: number[][]): number[][] {
return zeros2D(a.length, a.length ? a[0].length : 0);
}
function clone2D(a: number[][]): number[][] {
return a.map((row) => row.slice());
}
function map2DBool(a: number[][], fn: (v: number) => boolean): boolean[][] {
return a.map((row) => row.map(fn));
}
function divide2D(a: number[][], v: number): number[][] {
return a.map((row) => row.map((x) => x / v));
}
function slice2D(a: number[][], rowStart: number, rowEnd: number, colStart: number, colEnd: number): number[][] {
const out: number[][] = [];
for (let y = rowStart; y < rowEnd; y++) {
out.push(a[y].slice(colStart, colEnd));
}
return out;
}
function median2D(a: number[][]): number {
const flat: number[] = [];
for (const row of a) {
for (const v of row) flat.push(v);
}
flat.sort((x, y) => x - y);
const n = flat.length;
if (n === 0) return NaN;
if (n % 2 === 1) return flat[(n - 1) / 2];
return (flat[n / 2 - 1] + flat[n / 2]) / 2;
}
/* =========================
* Example usage
* ========================= */
// const img = new RawImage(width, height, rgbaBytes, 4);
// const h1 = phash(img);
// const h2 = dhash(img);
// const h3 = whash(img);
// console.log(h1.toString(), h2.toString(), h3.toString());