Files
windows-fenjian/core/recognition/prep.py
T

173 lines
7.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""识别帧前处理:裁掉四周干扰 + 提亮降噪,只作用于「喂给模型」的那一份。
为什么要单独一层:相机 1280×720 是固定俯拍,画面里除了秤盘上的那件货,
还有黑筐边框、地面、墙、旁边的第二筐货,最要命的是操作员放手时留下的
半只手和一大片塑料袋反光。模型看到的是整帧,靠提示词一句「不要被带偏」
去兜,兜不住——现场 21:38 那袋土豆,手占了左上三分之一,模型先看到的是
手和袋子上的红字。
所以真正要做的不是多写两行提示词,而是**把干扰裁掉**。但绝不能动留档
照片:records.csv 里那列、上传服务端的凭证图,都必须是相机原帧。这里只
返回一份内存里的副本,原图一个像素都不碰。
参数都在 vision 段,现场可调,改完重启即可:
recog_prep 总开关(false 就完全按老样子整帧直发)
recog_crop 保留中心多少比例,0.5~1.0;1.0 = 不裁;默认 0.86
recog_enhance 提亮/降噪开关,默认 true
recog_quality 发给模型的 JPEG 质量,默认 88
不做「智能找主体」那种裁剪:秤是固定的、货是一袋一袋放的,检测一抖就会
把半袋货裁到画面外,比不裁更糟。要动就动中心固定比例,可预期、可回滚。
"""
import numpy as np
import cv2
# 提亮目标:灰度均值拉到这个水平就停手。140 左右既能让塑料袋里的货看清,
# 又不至于把深色筐底也拉成灰白(拉过头反而没对比)。
_TARGET_MEAN = 132.0
# 低于这个均值才认为「偏暗」,正常光线下不动
_DARK_MEAN = 100.0
# 低于这个标准差才认为「发灰、没对比」,才上 CLAHE
_FLAT_STD = 46.0
def read_image(path):
"""读图,兼容中文路径。
cv2.imread 在 Windows 上走窄字符 fopen,D:\\入库分拣抓拍 这种中文路径
会静默返回 None(frames._save 的注释里记过同一个坑,写的那头绕开了,
读的这头原来没绕)。改用 np.fromfile + imdecode,宽字符 API。
"""
try:
buf = np.fromfile(path, dtype=np.uint8)
except (OSError, ValueError):
return None
if buf is None or buf.size == 0:
return None
return cv2.imdecode(buf, cv2.IMREAD_COLOR)
def encode_jpeg(img, quality=88):
ok, buf = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY),
int(quality)])
return buf.tobytes() if ok else None
def crop_center(img, keep=0.86):
"""保留中心 keep 比例的区域;keep>=1 原样返回。"""
h, w = img.shape[:2]
try:
keep = float(keep)
except (TypeError, ValueError):
keep = 0.86
if keep >= 0.999 or keep <= 0.2:
return img
cw, ch = int(round(w * keep)), int(round(h * keep))
x0, y0 = (w - cw) // 2, (h - ch) // 2
return img[y0:y0 + ch, x0:x0 + cw]
def _auto_gamma(img):
"""按灰度均值提亮,返回 (图, gamma)。只提亮不压暗。"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mean = float(gray.mean())
if mean >= _DARK_MEAN or mean <= 1.0:
return img, 1.0
import math
# LUT 指数:out = 255*(in/255)**power。power<1 提亮,>1 压暗。
# 由「均值 mean 打到 _TARGET_MEAN」反解,不是拍脑袋定的常数。
power = math.log(_TARGET_MEAN / 255.0) / math.log(mean / 255.0)
# 下限 0.55:现场这张 21:38 的帧均值只有 60(背光+黑筐),按 132 打会
# 把塑料袋噪点一起拉亮,反而更难认;宁可少提一点。
power = max(0.55, min(1.8, power))
if abs(power - 1.0) < 0.05:
return img, 1.0
lut = np.array([((i / 255.0) ** power) * 255
for i in range(256)], dtype=np.uint8)
# 对外报「提亮倍数」(1/power),比报指数直观:×1.56 就是亮了一倍半
return cv2.LUT(img, lut), round(1.0 / power, 2)
def _clahe(img):
"""在 LAB 的 L 通道做温和均衡,不动色相(火龙果的红、青椒的绿要保住)。"""
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clip = 2.0
grid = 8
l = cv2.createCLAHE(clipLimit=clip, tileGridSize=(grid, grid)).apply(l)
return cv2.cvtColor(cv2.merge([l, a, b]), cv2.COLOR_LAB2BGR)
def _sharpen(img, amount=0.45, sigma=1.1):
"""轻锐化:塑料袋隔着膜看货,边缘糊是主要问题,但过度会出光晕。"""
blur = cv2.GaussianBlur(img, (0, 0), sigma)
return cv2.addWeighted(img, 1.0 + amount, blur, -amount, 0)
def for_ai(frame, vcfg=None, max_px=None):
"""整帧 -> 识别用副本。返回 (图, meta)。
meta 进日志:哪次识别裁了多少、提亮到几倍,出问题能对上号。
"""
vcfg = vcfg or {}
meta = {'crop': 1.0, 'gamma': 1.0, 'clahe': False, 'sharp': False,
'from': None, 'to': None}
if frame is None or getattr(frame, 'size', 0) == 0:
return frame, meta
meta['from'] = '%dx%d' % (frame.shape[1], frame.shape[0])
keep = vcfg.get('recog_crop', 0.86)
out = crop_center(frame, keep)
try:
meta['crop'] = round(min(1.0, max(0.2, float(keep))), 3) \
if float(keep) < 0.999 else 1.0
except (TypeError, ValueError):
meta['crop'] = 1.0
# 先缩到目标尺寸再做增强:锐化要作用在最终像素上,否则缩完又糊回去
limit = max_px if max_px is not None else vcfg.get('recognition_image_max_px')
try:
limit = int(limit or 0)
except (TypeError, ValueError):
limit = 0
h, w = out.shape[:2]
long_edge = max(h, w)
if limit and long_edge > limit: # 只缩不放:放大不会多出信息
r = limit / float(long_edge)
out = cv2.resize(out, (max(1, int(w * r)), max(1, int(h * r))),
interpolation=cv2.INTER_AREA)
if vcfg.get('recog_enhance', True):
out, gamma = _auto_gamma(out)
meta['gamma'] = gamma
gray = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY)
if float(gray.std()) < _FLAT_STD:
out = _clahe(out)
meta['clahe'] = True
out = _sharpen(out)
meta['sharp'] = True
meta['to'] = '%dx%d' % (out.shape[1], out.shape[0])
return out, meta
def label(meta):
"""一行摘要,写进 dev 日志。"""
meta = meta or {}
if meta.get('error'):
return '前处理失败(%s),用原图' % meta['error']
if meta.get('crop', 1.0) >= 0.999 and meta.get('gamma', 1.0) == 1.0 \
and not meta.get('clahe'):
return '前处理:未改(%s)' % (meta.get('from') or '-')
bits = ['裁 %d%%' % round(float(meta.get('crop') or 1.0) * 100)]
if float(meta.get('gamma') or 1.0) != 1.0:
bits.append('提亮×%s' % meta['gamma'])
if meta.get('clahe'):
bits.append('均衡')
if meta.get('sharp'):
bits.append('锐化')
bits.append('%s→%s' % (meta.get('from') or '-', meta.get('to') or '-'))
return '前处理:' + ','.join(bits)