影刀RPA AI图像识别自动化:验证码与商品图片智能处理

影刀RPA AI图像识别自动化:验证码与商品图片智能处理

作者:林焱


什么情况用

做RPA自动化,最头疼的场景之一就是「流程卡在图像上」:

  • 登录时弹了个图形验证码,流程直接挂掉
  • 需要判断网页上的商品图片是否加载成功(还是显示404占位图)
  • 批量下载了上千张图片,需要筛选出含有人像的(用作头像)和纯产品图的
  • 每天要从监控截图中判断是否有异常画面

这些靠传统RPA的元素判断和OCR都搞不定。但调用AI图像识别接口,可以轻松解决。

核心场景:需要RPA「看懂」图片内容的自动化任务。


怎么做

第一步:选一个图像识别方案

根据需求挑合适的工具:

拼多多店群自动化上架方案

需求推荐方案成本
文字验证码识别打码平台(超级鹰/图鉴)1-2分/次
图片内容分类通义千问VL / GPT-4V几分钱/张

| 图片相似度对比 | OpenCV + 感知哈希 | 免费 |
| OCR文字提取 | 百度OCR / PaddleOCR | 有免费额度 |

第二步:文字验证码自动识别实战

图形验证码是RPA的头号杀手。接入打码平台是最实用的方案。

超级鹰为例,注册后拿到用户名、密码、软件ID。

importrequestsimportbase64fromhashlibimportmd5classChaojiyingClient:"""超级鹰打码平台接入"""def__init__(self,username,password,soft_id):self.username=username self.password=md5(password.encode()).hexdigest()self.soft_id=soft_id self.base_url="https://upload.chaojiying.net/Upload/Processing.php"defrecognize(self,image_path,code_type=1902):""" 识别验证码图片 code_type: 1902=常见4位英文数字, 1004=4位数字, 1005=5位数字 """withopen(image_path,"rb")asf:image_base64=base64.b64encode(f.read()).decode()payload={"user":self.username,"pass2":self.password,"softid":self.soft_id,"codetype":str(code_type),"file_base64":image_base64}resp=requests.post(self.base_url,data=payload,timeout=30)result=resp.json()ifresult["err_no"]==0:return{"success":True,"code":result["pic_str"],"code_id":result["pic_id"]}else:return{"success":False,"error":result["err_str"]}# 使用示例cj=ChaojiyingClient("your_username","your_password","123456")

影刀流程中的拧螺丝环节

  1. 截图验证码:用影刀的「截图元素」功能,精确截取验证码图片区域
  2. 保存到本地:截图保存到临时目录
  3. Python节点识别:调用打码平台返回识别结果
  4. 填写验证码:用「填写输入框」指令填入识别结果
  5. 容错处理:如果提交后提示验证码错误,重新截图再试

第三步:通义千问VL——让AI描述图片内容

通义千问的多模态版本可以直接接收图片URL或base64,然后回答关于图片的问题。

importrequestsimportbase64importjsonclassQwenVision:"""通义千问视觉模型调用"""def__init__(self,api_key):self.api_key=api_key self.url="https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"defask_about_image(self,image_path,question):"""上传图片并提问"""# 读取图片转base64withopen(image_path,"rb")asf:image_b64=base64.b64encode(f.read()).decode()headers={"Authorization":f"Bearer{self.api_key}","Content-Type":"application/json"}payload={"model":"qwen-vl-plus","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":f"data:image/png;base64,{image_b64}"}},{"type":"text","text":question}]}]}resp=requests.post(self.url,headers=headers,json=payload,timeout=30)returnresp.json()["choices"][0]["message"]["content"]defis_product_image(self,image_path):"""判断是否为商品图"""prompt="""判断这张图片是否是一张正常的商品展示图。 返回格式(只返回JSON): {"is_product": true/false, "reason": "简短理由"} 注意:商品图通常主体清晰、背景简洁。占位图、破损图、纯色图不是商品图。"""result=self.ask_about_image(image_path,prompt)try:returnjson.loads(result)except:return{"is_product":False,"reason":"解析失败"}# 使用示例# qw = QwenVision("your-api-key")# result = qw.is_product_image("product_001.jpg")

第四步:OpenCV感知哈希——图片相似度去重

电商采集经常会抓到大量重复的图片(同一商品不同角度、水印版本等)。用感知哈希做去重,不需要联网。

importcv2importnumpyasnpimportosfromcollectionsimportdefaultdictclassImageDeduplicator:"""图片去重——基于感知哈希"""@staticmethoddefperceptual_hash(image_path,hash_size=8):""" 计算图片的感知哈希值 相似的图片会产生相似的哈希值 """img=cv2.imread(image_path)ifimgisNone:returnNone# 缩放 + 灰度化img=cv2.resize(img,(hash_size+1,hash_size))gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# 计算差异哈希diff=gray[:,1:]>gray[:,:-1]returnsum(2**ifori,vinenumerate(diff.flatten())ifv)@staticmethoddefhamming_distance(hash1,hash2):"""汉明距离——越小越相似"""returnbin(hash1^hash2).count("1")defdeduplicate_folder(self,folder_path,threshold=5):""" 扫描文件夹,标记相似图片 汉明距离 <= threshold 视为重复 """image_files=[fforfinos.listdir(folder_path)iff.lower().endswith(('.png','.jpg','.jpeg','.bmp','.webp'))]hashes={}groups=defaultdict(list)forfinimage_files:path=os.path.join(folder_path,f)h=self.perceptual_hash(path)ifhisNone:continuehashes[f]=h# 两两比较files=list(hashes.keys())foriinrange(len(files)):forjinrange(i+1,len(files)):dist=self.hamming_distance(hashes[files[i]],hashes[files[j]])ifdist<=threshold:groups[files[i]].append(files[j])returndict(groups)# 使用dedup=ImageDeduplicator()# 参数设5很严格(几乎一样才算重复),设10较宽松duplicates=dedup.deduplicate_folder("./product_images",threshold=8)forkey,dupsinduplicates.items():print(f"{key}与以下图片相似:{dups}")

第五步:用PaddleOCR做本地免费OCR

不想花钱用百度OCR?PaddleOCR离线免费,识别效果也不错。

""" 准备工作:在影刀的Python节点里先pip安装 pip install paddlepaddle paddleocr """frompaddleocrimportPaddleOCRclassLocalOCR:"""本地免费OCR识别"""def__init__(self,use_gpu=False):self.ocr=PaddleOCR(use_angle_cls=True,lang='ch',use_gpu=use_gpu)defrecognize(self,image_path):"""识别图片中的文字"""results=self.ocr.ocr(image_path,cls=True)text_list=[]ifresultsandresults[0]:forlineinresults[0]:box=line[0]# 文字框坐标 [[x1,y1],[x2,y2],[x3,y3],[x4,y4]]text=line[1][0]# 识别出的文字confidence=line[1][1]# 置信度text_list.append({![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/56787c1a9b4c403690f1ca7281f1cb0e.png#pic_center)"text":text,"confidence":round(confidence,2),"box":box})returntext_listdefextract_number_from_image(self,image_path):"""从图片中提取金额等数字信息(常用于发票)"""texts=self.recognize(image_path)importre numbers=[]foritemintexts:matches=re.findall(r'[\d,]+\.?\d*',item["text"])numbers.extend(matches)returnnumbers# 使用# ocr = LocalOCR()# result = ocr.recognize("invoice.png")# for item in result:# print(f"识别文字: {item['text']}, 置信度: {item['confidence']}")

有什么坑

坑1:打码平台不是万能的

超级鹰这类平台对扭曲字母+噪点的传统验证码效果好(准确率80-90%),但对滑块验证码、点选验证码(让你点图中的红绿灯)基本无能为力。

实际体感:滑块验证码目前真没什么好办法,打码平台准确率低得离谱。如果遇到滑块验证,老老实实走手动介入——设置暂停等人工拉滑块。

坑2:PaddleOCR首次加载巨慢

PaddleOCR第一次加载模型的时候要下载模型文件,整个过程可能需要1-3分钟。如果你在影刀的Python节点里每次都PaddleOCR()新建实例,每张图都要加载一次,慢到怀疑人生。

TEMU店群如何管理运营?

解决方法:把OCR实例做成全局变量(单例模式),只在第一次创建。

# 全局单例_ocr_instance=Nonedefget_ocr():global_ocr_instanceif_ocr_instanceisNone:frompaddleocrimportPaddleOCR _ocr_instance=PaddleOCR(use_angle_cls=True,lang='ch')return_ocr_instance

坑3:大模型图像识别的token费用

通义千问VL按图片分辨率收费,一张1080p的图片可能吃掉几千token。如果你不加压缩,一天处理几百张图,账单直接炸了。

解决方法:上传前用Pillow压缩图片到合理分辨率(800x600足够识别验证码和商品图)。

fromPILimportImagedefcompress_image(input_path,output_path,max_size=800):img=Image.open(input_path)img.thumbnail((max_size,max_size),Image.LANCZOS)img.save(output_path,quality=70)# 质量70%肉眼几乎看不出

坑4:感知哈希对旋转和裁剪敏感

同一张图片旋转15度或裁剪了边角,感知哈希的汉明距离可能就大到被判定为不相似了。

解决方法:对于可能有旋转/裁剪的场景,先做图像对齐或添加多种哈希(均值哈希 + 差异哈希 + 感知哈希)交叉验证。

坑5:影刀截图存在色差

影刀的截图功能在不同分辨率、不同缩放比例的显示器上,截出来的图尺寸和颜色可能有细微差异。这会影响OCR和验证码识别的准确率。

解决方法:在影刀流程开始前检查屏幕缩放,或者把截图统一resize到固定尺寸再传给识别模块。


总结:AI图像识别让RPA从「瞎子」进化到「看得见」。文字验证码用打码平台便宜够用,图片内容理解用多模态大模型效果好但烧钱,去重和分类用OpenCV本地跑零成本。选对工具组合,别让图片成为自动化的拦路虎。