关于降噪去干扰的折腾Python图片验证码降噪-8邻里降噪我发现有用的第一篇文章就是这个。如果没记错的话,几年前就看过了。Python图片验证码降噪-8邻域降噪fromPILimportImagedefnoise_remove_pil(image_name,k):"""8邻域降噪args:image_name:图片文件名k:判断阈值Returns:"""defcalculate_noise_count(img_obj,w,h):"""计算非白人邻居个数Args:img_obj:imgobjw:widthh:heightReturns:count(int)"""count=0width,height=img_obj.sizefor_w_in[w-1,w,w+1]:for_h_in[h-1,h,h+1]:if_w_>width-1:continueif_h_>height-1:continueif_w_==wand_h_==h:continueifimg_obj.getpixel((_w_,_h_))<230:#因为是灰度图,小于230就设置为非白count+=1returncountimg=Image.open(image_name)#灰度gray_img=img.convert('L')w,h=gray_img.sizefor_winrange(w):for_hinrange(h):if_w==0or_h==0:gray_img.putpixel((_w,_h),255)continue#计算邻域内非白色像素的个数pixel=gray_img.getpixel((_w,_h))ifpixel==255:continueifcalculate_noise_count(gray_img,_w,_h)None:passdefocr(self,img):"""验证码OCRArgs:img(img):imgObject/imgPath返回:[string]:识别结果"""img_obj=Image.open(img)iftype(img)==strelseimgself._remove_pil(img_obj)verify_code=tesserocr.image_to_text(img_obj)returnverify_code.replace("\n","").strip()def_get_p_black_count(self,img:Image,_w:int,_h:int):"""获取当前位置周围像素的黑色元素个数args:img(img):图片信息_w(int):w坐标_h(int):h坐标Returns:int:number"""w,h=img.sizep_round_items=[]#超出横纵坐标if_w==0or_w==w-1or0==_hor_h==h-1:return0p_round_items=[img.getpixel((_w,_h-1)),img.getpixel((_w,_h+1)),img.getpixel(((_w-1,_h)),img.getpixel((_w+1,_h))]p_black_count=0forp_iteminp_round_items:ifp_item==(0,0,0):p_black_count=p_black_count+1返回p_black_countdef_remove_pil(self,img:Image):"""清理干扰识别的线条和噪声args:img(img):Image对象Returns:[img]:已清理的Image对象"""w,h=img.sizefor_winrange(w):for_hinrange(h):o_pixel=img.getpixel((_w,_h))#当前像素为红色(线段)或绿色(噪声)ifo_pixel==(255,0,0)oro_pixel==(0,0,255):#如果周围的黑色个数大于2,则用黑色填充当前像素;否则,用白色覆盖它,_h),(255,255,255))logger.info(f"_remove_pil完成。")#img.show()返回imgif__name__=='__main__':verfyCodeOCR=VerfyCodeOCR()img_path="./imgs/51.png"img=Image.open(img_path)img.show()ocr_result=verfyCodeOCR.ocr(img)img.show()logger.info(ocr_result)总结:识别率80%左右,部分相连的字符会被误识别,切割后需要将字符分开降噪算法只适用于当前图片,其他场景需要自行适配代码地址:https://github.com/liguobao/p...参考文章:宗小宝:Tesserocr库的安装与使用雷迪:tesserocr安装Python图片验证码降噪-8种常用颜色用于邻域降噪的RGB值-general001-博客园Python爬虫过程中遇到的带有干扰线的简单验证码处理方法