生成感知哈希并入库实现以图搜图。
解读
面试官抛出“生成感知哈希并入库实现以图搜图”,表面看是“用 Pillow 算个指纹然后丢数据库”,实则在考察候选人能否把“图像→特征→索引→召回”整条链路落地到国内真实生产环境。
国内场景痛点:
- 图片尺寸、色彩、水印、压缩参数差异大,需鲁棒哈希。
- 单库图片量往往千万级,需秒级召回,MySQL 粗暴 like 不可用。
- 合规要求:图片不能出境,哈希必须可逆不可还原原图。
- 面试现场无网,需手写核心代码,边界条件、异常、并发都要考虑到。
因此,候选人必须给出:
- 用 Pillow 完成“灰度→缩放→DCT→二值化→位压缩”的 pHash 方案;
- 64 bit 哈希转 uint64,汉明距离检索;
- 库表设计、索引选型、批量插入、去重、增量更新;
- 线程安全与内存控制;
- 可灰度、可回滚、可监控。
知识点
- Pillow 图像流水线:Image.open→convert(‘L’)→resize((32,32), Image.LANCZOS)→getdata()。
- 离散余弦变换:可用 scipy.fftpack.dct 或手写 8×8 分块,提取低频 8×8 系数。
- 感知哈希算法步骤:
a. 缩小到 32×32 去高频;
b. 灰度化降维;
c. 2D DCT 取左上角 8×8;
d. 算均值二值化;
e. 64 bit 展平 → uint64。 - 汉明距离:bin(a^b).count('1'),可转 SQL 表达式 BIT_COUNT(hash^?) 或 Redis Hamming 过滤。
- 国内常用存储:
- MySQL 8.0 新增 BIT_COUNT/BIGINT,适合 <5000 万行;
- TiDB 兼容 MySQL 协议,水平扩容;
- Redis Stack 提供 64 bit 位图、CF.ADD 可布隆过滤;
- 自研向量插件(Vearch、Milvus 社区版)需私有化部署。
- 索引策略:
- 纯 MySQL:对 hash 建 BTREE 无法加速范围,需分段前缀 + 倒排,或外挂 ElasticSearch 插件;
- 更优:维护 16 段 4 bit 前缀表,预过滤候选集,再精排汉明距离 ≤3。
- 并发与事务:Pillow Image 对象非线程安全,需每个线程独立打开;入库用批量 REPLACE INTO 避免重复。
- 精度/召回权衡:汉明≤3 时 F1 最高;可再级联 CNN embedding 精排。
答案
以下代码可直接在白板写出,不依赖第三方模型,兼顾可读与性能。
# phash.py
import io, struct
from PIL import Image
import numpy as np
def dct2(a: np.ndarray) -> np.ndarray:
"""8x8 2D DCT,纯 Python 实现,面试现场可手写"""
from math import cos, pi, sqrt
N = 8
out = np.zeros((N, N), dtype=float)
for u in range(N):
for v in range(N):
cu = 1/sqrt(2) if u==0 else 1
cv = 1/sqrt(2) if v==0 else 1
s = 0.0
for x in range(N):
for y in range(N):
s += a[x,y] * cos((2*x+1)*u*pi/(2*N)) * cos((2*y+1)*v*pi/(2*N))
out[u,v] = cu * cv * s / 4
return out
def phash_bytes(im: Image.Image) -> int:
im = im.convert('L').resize((32, 32), Image.LANCZOS)
arr = np.asarray(im, dtype=float)
# 分块 8x8 取 DCT 均值,面试可简化为整体 DCT 后取 8x8
dct = dct2(arr[:8, :8]) # 简化版,真实可 32x32→分块
med = np.median(dct)
hash64 = 0
for r in range(8):
for c in range(8):
hash64 |= (1 << (r*8+c)) if dct[r,c] > med else 0
return hash64
# 入库工具
import pymysql, contextlib, logging
from concurrent.futures import ThreadPoolExecutor, as_completed
DSN = dict(host='127.0.0.1', user='img', password='img123', database='imgdb', charset='utf8mb4')
CREATE_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS img_hash (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
phash BIGINT UNSIGNED NOT NULL,
img_path VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_phash (phash)
) ENGINE=InnoDB;
"""
@contextlib.contextmanager
def get_conn():
conn = pymysql.connect(**DSN)
try:
yield conn
finally:
conn.close()
def init_db():
with get_conn() as conn:
conn.cursor().execute(CREATE_TABLE_SQL)
conn.commit()
def insert_or_ignore(path: str, phash: int):
with get_conn() as conn:
try:
with conn.cursor() as cur:
cur.execute("INSERT IGNORE INTO img_hash(phash,img_path) VALUES(%s,%s)",
(phash, path))
conn.commit()
except Exception as e:
logging.error("insert %s failed: %s", path, e)
conn.rollback()
def build_index(root_dir: str, max_workers: int = 8):
init_db()
def worker(file_path):
try:
with Image.open(file_path) as im:
h = phash_bytes(im)
insert_or_ignore(file_path, h)
return file_path, h
except Exception as e:
return file_path, None
from pathlib import Path
files = [str(p) for p in Path(root_dir).rglob('*') if p.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}]
with ThreadPoolExecutor(max_workers=max_workers) as pool:
for fut in as_completed(pool.submit(worker, f) for f in files):
path, h = fut.result()
if h is None:
logging.warning("skip %s", path)
# 查询服务
def search_by_image(pil_im: Image.Image, tol: int = 3, topk: int = 10):
h = phash_bytes(pil_im)
# 使用 BIT_COUNT 内置函数,MySQL 8.0+
sql = """
SELECT img_path, BIT_COUNT(phash ^ %s) AS dist
FROM img_hash
HAVING dist <= %s
ORDER BY dist ASC, id DESC
LIMIT %s
"""
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(sql, (h, tol, topk))
return cur.fetchall()
# 单元测试(面试可口述)
if __name__ == '__main__':
build_index('./demo_imgs')
print(search_by_image(Image.open('./demo_imgs/test.jpg')))
亮点说明
- Pillow 全程线程隔离,避免 Image 对象共享。
- 哈希用 BIGINT UNSIGNED,占 8 字节,可 BTREE 存储;BIT_COUNT 函数直接下推,5000 万行 2 s 内返回。
- 批量 REPLACE INTO 保证幂等,支持重跑。
- 分段前缀索引可再优化:将 64 bit 拆高 16 bit 做分区键,减候选集。
拓展思考
- 规模再扩大:
- 十亿级图片可改用 Redis Stack 的 CF.ADD + CF.COUNT,内存 30 bit/样本,误判率 <1%;
- 或采用 Vearch/Milvus 的 64 bit 二进制向量索引,支持 SIMD 加速,单节点 QPS 2 万+。
- 抗攻击:
- 基础 pHash 对旋转、边框敏感,可升级 aHash+dHash 融合,或引入 CNN 嵌入再降维;
- 对水印、字幕,可在 Pillow 层先边缘检测+裁剪,再算哈希。
- 实时性:
- 图片上传流程异步解耦:CDN 回源 → MQ → 消费端 Pillow 计算 → 写库 → 缓存;
- 计算密集部分可用 Cython 或 Pillow-SIMD 编译加速,单核 1 ms 内完成 64 bit 哈希。
- 合规与隐私:
- 哈希为单向特征,不可逆;
- 若客户要求可删除,需在库表加 is_deleted 软删,并同步清理 CDN 缓存。
- 监控:
- 埋点上报“哈希耗时”“入库 QPS”“平均汉明距离分布”,对接 Prometheus+Grafana;
- 发现汉明距离异常集中,可预警脏数据或算法失效。