优化彩色课表占用识别,仅记录有课无课并简化校对

This commit is contained in:
2026-11-12 16:21:32 +08:00
parent 0dbb5063ec
commit 2c6e12f831
6 changed files with 387 additions and 70 deletions
+282 -53
View File
@@ -1,5 +1,9 @@
"""本地图片识别及值班时段整理。留白保持待确认,不能直接当作空闲。"""
import io
import copy
import hashlib
import time
from collections import OrderedDict
import re
import threading
import unicodedata
@@ -16,6 +20,8 @@ SLOTS = [
DAYS = ['周一', '周二', '周三', '周四', '周五']
_engine = None
_lock = threading.Lock()
_cache = OrderedDict()
_cache_lock = threading.Lock()
def blank_structure():
@@ -33,7 +39,7 @@ def normalize_image(raw):
if getattr(image, 'n_frames', 1) != 1:
raise ValueError('请上传静态课表图片')
image = ImageOps.exif_transpose(image).convert('RGB')
output = io.BytesIO(); image.save(output, 'PNG')
output = io.BytesIO(); image.save(output, 'PNG', compress_level=1)
return output.getvalue()
@@ -43,7 +49,8 @@ def read_image(raw):
if _engine is None:
from rapidocr import RapidOCR
_engine = RapidOCR(params={
'Global.log_level': 'error', 'Global.max_side_len': 2400,
'Global.log_level': 'error', 'Global.max_side_len': 2000,
'Det.limit_side_len': 1600, 'Det.limit_type': 'max',
'EngineConfig.onnxruntime.intra_op_num_threads': 2,
'EngineConfig.onnxruntime.inter_op_num_threads': 1,
})
@@ -60,6 +67,10 @@ def compact(value):
def weekday(text):
value = compact(text)
if value in '一二三四五六日天' and len(value)==1:
return 7 if value in '日天' else '一二三四五六'.index(value)+1
if value in ('-', '—', '一'):
return 1
match = re.match(r'^(?:星期|礼拜|周)([一二三四五六日天1-7])', value)
if match:
token = match[1]
@@ -69,81 +80,299 @@ def weekday(text):
def periods(text):
value = compact(text).replace('第', '').replace('节次', '').replace('节', '')
value = value.replace('—', '-').replace('–', '-')
chinese = {'一二': [1, 2], '三四': [3, 4], '五六': [5, 6], '七八': [7, 8]}
if len(value) == 1 and value in '一二三四五六七八': return ['一二三四五六七八'.index(value) + 1]
if value.replace('、', '') in chinese: return chinese[value.replace('、', '')]
if value in chinese: return chinese[value]
match = re.fullmatch(r'(\d{1,2})(?:[-~至、](\d{1,2}))?', value)
value = compact(text).replace('节次', '节').replace('第', '')
value = re.sub(r'[—–-~~至]', '-', value)
# 时间、周次和课程名中的数字不能当作节次。
value = re.split(r'节|[((\[]|\n', value, maxsplit=1)[0]
chinese = {word: i for i, word in enumerate(('一','二','三','四','五','六','七','八','九','十','十一','十二'), 1)}
if value in chinese: return [chinese[value]]
for pair in ('一二', '三四', '五六', '七八', '九十'):
if value.replace('、', '') == pair:
return [chinese[pair[0]], chinese[pair[1]]]
for word, number in sorted(chinese.items(), key=lambda item: -len(item[0])):
value = value.replace(word, str(number))
match = re.fullmatch(r'(\d{1,2})(?:[-、,](\d{1,2}))?', value)
if not match: return []
start = int(match[1]); end = int(match[2] or start)
return list(range(start, end + 1)) if 1 <= start <= end <= 12 else []
def structure_from_lines(lines):
result = blank_structure()
result['raw_text'] = '\n'.join(line['text'] for line in lines)[:100000]
result['warnings'] = ['识别结果需核对。未识别到文字的时段保持待确认,不自动判为空闲。']
def _positioned(lines):
positioned = []
for line in lines:
xs = [point[0] for point in line['box']]; ys = [point[1] for point in line['box']]
positioned.append({**line, 'x': (min(xs) + max(xs)) / 2, 'y': (min(ys) + max(ys)) / 2,
'height': max(ys) - min(ys)})
'top': min(ys), 'bottom': max(ys), 'height': max(ys) - min(ys)})
return positioned
def _columns(positioned):
headers = [line for line in positioned if weekday(line['text'])]
groups = []
candidates = []
for header in headers:
group = [line for line in headers if abs(line['y'] - header['y']) < max(15, header['height'] * 1.5)]
groups.append(group)
selected = max(groups, key=lambda group: len({weekday(line['text']) for line in group}), default=[])
columns = {weekday(line['text']): line['x'] for line in selected}
if not all(day in columns for day in range(1, 6)) or any(columns[d] >= columns[d+1] for d in range(1, 5)):
result['warnings'].append('未能完整定位周一至周五列,请对照原图手动整理。')
return result
step = median(columns[d+1] - columns[d] for d in range(1, 5))
left = columns[1] - step / 2
header_y = median(line['y'] for line in selected)
columns = {}
for line in group:
columns.setdefault(weekday(line['text']), []).append(line['x'])
unique = {day:xs[0] for day,xs in columns.items() if len(xs)==1}
days = sorted(unique)
if len(days)>=3:
guessed_step=median((unique[b]-unique[a])/(b-a) for a,b in zip(days,days[1:]))
origin=median(unique[d]-(d-1)*guessed_step for d in days)
columns={day:min(xs,key=lambda x:abs(x-(origin+(day-1)*guessed_step))) for day,xs in columns.items()}
else:
columns={day:median(xs) for day,xs in columns.items()}
days = sorted(columns)
if len(days) < 3: continue
step = median((columns[b] - columns[a]) / (b-a) for a,b in zip(days, days[1:]))
if step <= 0: continue
origin = median(columns[day] - (day-1)*step for day in days)
if any(abs(columns[day] - (origin+(day-1)*step)) > step*.2 for day in days): continue
candidates.append((len(days), -median(line['y'] for line in group), origin, step, columns, group))
if not candidates: return None
_, _, origin, step, columns, group = max(candidates, key=lambda item: item[:2])
inferred = [day for day in range(1,6) if day not in columns]
# 内部漏字可内插;至少5个星期锚点时仅外推相邻的一列,并在图像路径核对边界。
usable = {day: columns.get(day, origin+(day-1)*step) for day in range(1,6)
if min(columns)<=day<=max(columns) or (len(columns)>=5 and min(columns)-1<=day<=max(columns)+1)}
return usable, step, median(line['y'] for line in group), inferred
def _rows(positioned, left, header_y):
anchors = {slot['id']: [] for slot in SLOTS}
section_y = {}
for line in positioned:
if line['x'] >= left or line['y'] <= header_y: continue
nums = periods(line['text'])
if nums and len(nums) <= 2:
if nums:
for number in nums:
section_y.setdefault(number, []).append(line['y'])
for index, slot in enumerate(SLOTS):
if any(number in (index * 2 + 1, index * 2 + 2) for number in nums):
if any(number in (index*2+1,index*2+2) for number in nums):
anchors[slot['id']].append(line['y'])
value = compact(line['text'])
value = compact(line['text']).replace(':', ':')
for slot in SLOTS:
if re.match(r'^0?' + re.escape(slot['start'].lstrip('0')) + r'(?:$|[-~])', value):
anchors[slot['id']].append(line['y'])
if not all(anchors.values()):
result['warnings'].append('未能完整定位一二、三四、五六、七八节,请手动核对时段。')
if re.match(r'^0?' + re.escape(slot['start'].lstrip('0')) + r'(?:$|[-~~—])', value):
# 有节次文字时优先节次,避免小号时间标签拉偏行中心。
if not anchors[slot['id']]: anchors[slot['id']].append(line['y'])
# OCR可能把晚间的9读成6;重复节次用前后节次定位,不能把行中心拉到晚间。
for number,ys in section_y.items():
if len(ys)>1 and number-1 in section_y and number+1 in section_y:
expected=(median(section_y[number-1])+median(section_y[number+1]))/2
section_y[number]=[min(ys,key=lambda y:abs(y-expected))]
centers={}
for i,slot in enumerate(SLOTS):
ys=[median(section_y[n]) for n in (i*2+1,i*2+2) if n in section_y]
if ys: centers[i]=median(ys)
elif anchors[slot['id']]: centers[i]=median(anchors[slot['id']])
known = sorted(centers)
if len(known) < 2 or any(centers[a] >= centers[b] for a,b in zip(known,known[1:])):
return {}, []
step = median((centers[b]-centers[a])/(b-a) for a,b in zip(known,known[1:]))
if any(not step*.5 <= (centers[b]-centers[a])/(b-a) <= step*1.8 for a,b in zip(known,known[1:])):
return {}, []
inferred = []
# 仅内插一个漏识别的行,保留无法确定的首尾行。
if len(known) >= 3:
for i in range(min(known),max(known)+1):
if i not in centers:
lo=max(k for k in known if k<i);hi=min(k for k in known if k>i)
centers[i]=centers[lo]+(centers[hi]-centers[lo])*(i-lo)/(hi-lo);inferred.append(i)
rows = {}
for i,center in centers.items():
top = (centers[i-1]+center)/2 if i-1 in centers else center-step/2
bottom = (center+centers[i+1])/2 if i+1 in centers else center+step/2
# 晚间节次定位最后一行下沿,防止夜课被算入七八节。
if i == 3 and 9 in section_y:
bottom = min(bottom,(max(section_y.get(8,[center]))+min(section_y[9]))/2)
rows[i]=(top,bottom)
return rows, inferred
def course_blocks(raw):
"""常见彩色课程卡片的边界,用于还原跨节课程;无明确边界时使用文字位置。"""
import cv2
import numpy as np
with Image.open(io.BytesIO(raw)) as image:
original = image.size
image = image.convert('RGB'); image.thumbnail((1200,1200))
rgb = np.array(image)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
sx,sy=original[0]/rgb.shape[1],original[1]/rgb.shape[0]
blocks=[]
# 按色相分开连通区域,紧贴的红、绿、蓝课程卡片不能粘成一个大块。
for hue in range(0,180,15):
distance=np.abs(hsv[:,:,0].astype('int16')-hue)
distance=np.minimum(distance,180-distance)
mask=((distance<=12)&(hsv[:,:,1]>=28)&(hsv[:,:,2]>=100)).astype('uint8')*255
mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,np.ones((3,3),np.uint8))
mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,np.ones((3,3),np.uint8))
count,_,stats,_=cv2.connectedComponentsWithStats(mask,connectivity=4)
blocks.extend((float(x*sx),float(y*sy),float((x+w)*sx),float((y+h)*sy))
for x,y,w,h,area in stats[1:count] if w>=15 and h>=20 and area>=w*h*.6)
# 重叠色域避免JPEG边缘色差切碎卡片;只保留未被较大矩形覆盖的区域。
kept=[]
for box in sorted(blocks,key=lambda b:(b[2]-b[0])*(b[3]-b[1]),reverse=True):
x1,y1,x2,y2=box;area=(x2-x1)*(y2-y1)
if any(max(0,min(x2,b[2])-max(x1,b[0]))*max(0,min(y2,b[3])-max(y1,b[1]))>=area*.9 for b in kept):continue
kept.append(box)
return kept
def structure_from_lines(lines, blocks=()):
result = blank_structure()
result['raw_text'] = '\n'.join(line['text'] for line in lines)[:100000]
result['warnings'] = ['识别结果需核对。未识别到文字的时段保持待确认,不自动判为空闲。']
positioned = _positioned(lines)
layout = _columns(positioned)
if not layout:
result['warnings'].append('星期列定位不足,请保留完整表头并对照原图整理。')
return result
centers = [median(anchors[slot['id']]) for slot in SLOTS]
if any(centers[i] >= centers[i+1] for i in range(3)):
result['warnings'].append('节次位置不明确,请手动整理。')
return result
bounds = [centers[0] - (centers[1] - centers[0]) / 2,
*[(centers[i] + centers[i+1]) / 2 for i in range(3)],
centers[-1] + (centers[-1] - centers[-2]) / 2]
columns, step, header_y, inferred_days = layout
if inferred_days:
result['warnings'].append('部分星期文字未识别,已参考相邻列定位;请重点核对。')
left = min(columns.values()) - step/2
rows, inferred_rows = _rows(positioned,left,header_y)
if len(rows)<4:
result['warnings'].append('部分节次未定位,已保留可定位时段,其余请手动核对。')
if inferred_rows:
result['warnings'].append('部分节次标签漏识别,已参考相邻行定位;请重点核对。')
if not rows: return result
cells = {(cell['day'], cell['slot']): cell for cell in result['cells']}
for line in positioned:
day = min(range(1, 6), key=lambda d: abs(line['x'] - columns[d]))
if abs(line['x'] - columns[day]) >= step / 2 or line['y'] <= header_y: continue
row = next((i for i in range(4) if bounds[i] <= line['y'] < bounds[i+1]), None)
if row is None: continue
for line in sorted(positioned,key=lambda line:(line['y'],line['x'])):
if not columns: continue
day = min(columns, key=lambda d: abs(line['x'] - columns[d]))
if abs(line['x'] - columns[day]) >= step/2 or line['y'] <= header_y: continue
text = compact(line['text'])
if not text: continue
cell = cells[(day, SLOTS[row]['id'])]
empty = text in ('无课', '空闲', '无课程')
if empty:
if cell['status'] == 'unknown' and line['score'] >= .9:
cell.update(status='free', confidence=line['score'])
if not text or weekday(text) or re.fullmatch(r'\d{1,2}[::]\d{2}(?:[-—~~]\d{1,2}[::]\d{2})?',text): continue
row = next((i for i,(top,bottom) in rows.items() if top<=line['y']<bottom),None)
if row is None: continue
target_rows = [row]
# 文本中明确的“3-6节”比文字中心位置可靠。
explicit = re.search(r'(?:第)?(\d{1,2})[-—~~至](\d{1,2})节',text)
if explicit and 1<=int(explicit[1])<=int(explicit[2])<=12:
target_rows = [i for i in rows if any(n in (i*2+1,i*2+2) for n in range(int(explicit[1]),int(explicit[2])+1))]
else:
cell['status'] = 'busy'
cell['courses'] = (cell['courses'] + '\n' + line['text']).strip()[:500]
cell['confidence'] = min(cell['confidence'] or 1, line['score'])
block = next(((x1,y1,x2,y2) for x1,y1,x2,y2 in blocks
if x1<=line['x']<=x2 and y1<=line['y']<=y2 and step*.45<=x2-x1<=step*1.15
and y2-y1>=line['height']*1.5),None)
if block:
_,y1,_,y2=block
target_rows = [i for i,(top,bottom) in rows.items()
if min(y2,bottom)-max(y1,top)>min(y2-y1,bottom-top)*.2]
empty = text in ('无课', '空闲', '无课程')
for i in target_rows:
cell = cells[(day,SLOTS[i]['id'])]
if empty:
if cell['status']=='unknown' and line['score']>=.9:
cell.update(status='free',confidence=line['score'])
else:
# 低分文本提示核对,不能据此推断空闲。
cell['status']='busy'
if line['text'] not in cell['courses'].split('\n'):
cell['courses']=(cell['courses']+'\n'+line['text']).strip()[:500]
cell['confidence']=min(cell['confidence'] or 1,line['score'])
return result
def layout_lines(raw, blocks):
"""把表头和左侧节次拼成一张小图,只识别定位文字,跳过课程正文。"""
with Image.open(io.BytesIO(raw)) as image:
image=image.convert('RGB');width,height=image.size
cards=[b for b in blocks if width*.06<=b[2]-b[0]<=width*.85 and b[3]-b[1]>=height*.055]
if not cards: return []
table_top=int(min(b[1] for b in cards))
# 周一或上午可能完全无课,首个课程块不能直接当成表格左沿/表头下沿。
rail_right=int(min(min(b[0] for b in cards),width*.18))
if not width*.04<=rail_right<=width*.25: return []
if table_top>height*.3:
table_top=int(height*.3)
header_top=0
else:
header_top=max(0,table_top-int(width*.28))
crops=[(0,header_top,width,table_top)]
tile_height=440;gap=20
for top in range(table_top,height,tile_height-40):
crops.append((0,top,rail_right,min(top+tile_height,height)))
header_height=table_top-header_top
canvas=Image.new('RGB',(max(width,(rail_right+gap)*(len(crops)-1)),header_height+gap+tile_height),'white')
transforms=[]
for i,(x1,y1,x2,y2) in enumerate(crops):
dx,dy=(0,0) if i==0 else ((i-1)*(rail_right+gap),header_height+gap)
canvas.paste(image.crop((x1,y1,x2,y2)),(dx,dy))
transforms.append((dx,dy,dx+x2-x1,dy+y2-y1,x1-dx,y1-dy))
encoded=io.BytesIO();canvas.save(encoded,'PNG',compress_level=1)
mapped=[];seen=set()
for line in read_image(encoded.getvalue()):
x=median(p[0] for p in line['box']);y=median(p[1] for p in line['box'])
transform=next((t for t in transforms if t[0]<=x<t[2] and t[1]<=y<t[3]),None)
if transform:
ox,oy=transform[4:]
key=(line['text'],round(x+ox),round(y+oy))
if key in seen:continue
seen.add(key)
mapped.append({**line,'box':[[px+ox,py+oy] for px,py in line['box']]})
return mapped
def occupancy_from_blocks(lines, blocks, image_size):
"""完整定位的彩色周课表按课程块覆盖判断有课/无课,不依赖课程文字。"""
positioned=_positioned(lines);layout=_columns(positioned)
if not layout: return None
columns,step,header_y,inferred_days=layout
if len(columns)!=5 or len(inferred_days)>1: return None
rows,inferred_rows=_rows(positioned,min(columns.values())-step/2,header_y)
if len(rows)!=4 or inferred_rows:return None
width,height=image_size
if not width*.04<=columns[1]-step/2<=width*.25 or columns[5]+step/2>width:return None
# 一楼四个时段必须完整出现在截图中,裁切的末行不能被当作无课。
if min(top for top,_ in rows.values())<=header_y or max(bottom for _,bottom in rows.values())>height:
return None
cards=[]
for x1,y1,x2,y2 in blocks:
if y1<=header_y or y2-y1<min(bottom-top for top,bottom in rows.values())*.35:continue
if not step*.5<=x2-x1<=step*3.2:continue
if any(min(x2,x+step/2)-max(x1,x-step/2)>step*.5 for x in columns.values()):cards.append((x1,y1,x2,y2))
if not cards:return None
result=blank_structure()
result['method']='color_blocks'
result['warnings']=['已按彩色课程块整理有课/无课,跨节课程按覆盖时段记录。请对照原图核对后确认。']
for cell in result['cells']:
x=columns[cell['day']];top,bottom=rows[SLOT_INDEX[cell['slot']]]
busy=any(min(x2,x+step/2)-max(x1,x-step/2)>step*.5
and min(y2,bottom)-max(y1,top)>min(y2-y1,bottom-top)*.2 for x1,y1,x2,y2 in cards)
cell.update(status='busy' if busy else 'free',confidence=.95,source='image')
return result
SLOT_INDEX={slot['id']:i for i,slot in enumerate(SLOTS)}
def recognize(raw):
return structure_from_lines(read_image(raw))
started = time.perf_counter()
key = hashlib.sha256(raw).digest()
with _cache_lock:
cached = _cache.get(key)
if cached is not None:
_cache.move_to_end(key)
result = copy.deepcopy(cached)
result['recognition_ms']=round((time.perf_counter()-started)*1000)
result['cache_hit']=True
return result
blocks=course_blocks(raw)
lines=layout_lines(raw,blocks)
with Image.open(io.BytesIO(raw)) as image: size=image.size
result=occupancy_from_blocks(lines,blocks,size) if lines else None
if result is None:
result=structure_from_lines(read_image(raw),blocks)
result['method']='text_fallback'
result['warnings'].append('未能可靠定位彩色课表,未确定的位置请手动选择有课或无课。')
# 只保留时段占用状态,不收集课程名、教师及教室。
result['raw_text']=''
for cell in result['cells']:cell['courses']=''
result['recognition_ms']=round((time.perf_counter()-started)*1000)
result['cache_hit']=False
with _cache_lock:
_cache[key]=copy.deepcopy(result)
while len(_cache)>16: _cache.popitem(last=False)
return result