"""OCR Tesseract, detección de componentes y rostros (OpenCV), local.""" import argparse,json,subprocess,tempfile,shutil from pathlib import Path import cv2,numpy as np def load(path): if Path(path).stat().st_size>30*1024*1024:raise ValueError('Imagen >30 MiB') im=cv2.imdecode(np.fromfile(path,dtype=np.uint8),cv2.IMREAD_COLOR) if im is None or im.shape[0]*im.shape[1]>20_000_000:raise ValueError('Imagen inválida o demasiado grande') return im def regions(im,threshold=180,min_area=200): gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY);_,mask=cv2.threshold(gray,threshold,255,cv2.THRESH_BINARY_INV) n,_,stats,_=cv2.connectedComponentsWithStats(mask,8);return [[int(x),int(y),int(w),int(h),int(area)] for x,y,w,h,area in stats[1:] if area>=min_area] def faces(im): model=cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml') if model.empty():raise RuntimeError('Clasificador Haar no disponible') return [list(map(int,b)) for b in model.detectMultiScale(cv2.equalizeHist(cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)),scaleFactor=1.1,minNeighbors=5,minSize=(30,30))] def ocr(im,lang): if not shutil.which('tesseract'):raise RuntimeError('Instala Tesseract y añade su ejecutable a PATH') if lang not in ('eng','spa','eng+spa'):raise ValueError('Idioma no admitido en esta práctica') with tempfile.TemporaryDirectory() as d: p=Path(d)/'input.png';cv2.imwrite(str(p),im) return subprocess.run(['tesseract',str(p),'stdout','-l',lang,'--psm','6'],check=True,capture_output=True,text=True,encoding='utf-8',timeout=90).stdout.strip() def demo(): im=np.full((320,800,3),255,np.uint8);cv2.rectangle(im,(40,40),(140,140),(0,0,0),-1);cv2.circle(im,(300,100),45,(0,0,0),-1);assert len(regions(im))==2 text=np.full((180,900,3),255,np.uint8);cv2.putText(text,'APPINITDEV LAB',(24,110),cv2.FONT_HERSHEY_SIMPLEX,2.2,(0,0,0),4,cv2.LINE_AA) recognized=ocr(text,'eng');assert 'APPINITDEV' in recognized.upper(),recognized return {'components':2,'ocr':recognized,'faces_in_synthetic_shapes':len(faces(im))} def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('mode',choices=['demo','ocr','regions','faces']);p.add_argument('image',nargs='?');p.add_argument('--language',default='spa');p.add_argument('--output');a=p.parse_args() if a.mode=='demo':r=demo() else: if not a.image:p.error('Se requiere imagen') im=load(a.image) if a.mode=='ocr':r={'text':ocr(im,a.language)} else: boxes=regions(im) if a.mode=='regions' else faces(im);r={'count':len(boxes),'boxes_xywh':boxes} if a.output: if Path(a.output).exists():raise FileExistsError(a.output) for x,y,w,h,*_ in boxes:cv2.rectangle(im,(x,y),(x+w,y+h),(0,150,0),2) if not cv2.imwrite(a.output,im):raise OSError('No se pudo guardar') print(json.dumps(r,ensure_ascii=False,indent=2)) if __name__=='__main__':main()