前言
上一篇文章寫了自己搭建環(huán)境、處理圖片、識(shí)別驗(yàn)證碼等具體操作(上一篇文章地址)。對(duì)于沒有經(jīng)驗(yàn)的小伙伴來說,還是比較麻煩的,而且如果訓(xùn)練集處理的不好,識(shí)別率會(huì)非常低,所以上一篇文章可以作為學(xué)習(xí)參考,使用的話,我個(gè)人覺得本篇文章比較適合入手。
首先感謝大佬的開源模塊《帶帶弟弟OCR通用驗(yàn)證碼識(shí)別SDK免費(fèi)開源版》
地址:https://pypi.org/project/ddddocr/
DDDDocr介紹
ddddocr是由sml2h3開發(fā)的專為驗(yàn)證碼廠商進(jìn)行對(duì)自家新版本驗(yàn)證碼難易強(qiáng)度進(jìn)行驗(yàn)證的一個(gè)python庫,其由作者與kerlomz共同合作完成,通過大批量生成隨機(jī)數(shù)據(jù)后進(jìn)行深度網(wǎng)絡(luò)訓(xùn)練,本身并非針對(duì)任何一家驗(yàn)證碼廠商而制作,本庫使用效果完全靠玄學(xué),可能可以識(shí)別,可能不能識(shí)別。
ddddocr奉行著開箱即用、最簡(jiǎn)依賴的理念,盡量減少用戶的配置和使用成本,希望給每一位測(cè)試者帶來舒適的體驗(yàn)
項(xiàng)目地址: https://github.com/sml2h3/ddddocr
搭建準(zhǔn)備工作
1.python3.9以下環(huán)境 (直接百度一大堆)
2.Windows/Linux/Macos(暫時(shí)不支持Macbook M1(X),M1(X)用戶需要自己編譯onnxruntime才可以使用)
3.需要用的的庫
pip install uvicorn
pip install fastapi
pip install base64
pip install ddddocr
pip install PIL
準(zhǔn)備工作做完,可以直接上代碼了
代碼實(shí)現(xiàn)
import uvicorn
from fastapi import FastAPI, Body
import base64
import ddddocr
from io import BytesIO
from PIL import Image
app = FastAPI(title='文檔', description='by:juzi', version="1.0.4")
@app.post("/code", summary='識(shí)別圖片內(nèi)文字/字母', description='普通圖片驗(yàn)證碼識(shí)別,上傳圖片的Base64編碼', tags=['圖片驗(yàn)證碼識(shí)別'])
def identify_GeneralCAPTCHA(ImageBase64: str = Body(..., title='驗(yàn)證碼圖片Bse64文本', embed=True)):
base64_data = base64.b64decode(ImageBase64)
ocr = ddddocr.DdddOcr(show_ad=False)
res = ocr.classification(base64_data)
return {"result": res}
@app.post("/math", summary='識(shí)別算術(shù)驗(yàn)證碼', description='算術(shù)題驗(yàn)證碼識(shí)別,上傳圖片的Base64編碼,提供兩個(gè)返回,solution_result為識(shí)別結(jié)果', tags=['圖片驗(yàn)證碼識(shí)別'])
def identify_ArithmeticCAPTCHA(ImageBase64: str = Body(..., title='驗(yàn)證碼圖片Bse64文本', embed=True)):
base64_data = base64.b64decode(ImageBase64)
ocr = ddddocr.DdddOcr(show_ad=False)
res = ocr.classification(base64_data)
print("res:---------->" + res)
if "+" or '-' or 'x' or '/' or '÷' or '*' not in res:
zhi = "Calculation error"
if '+' in res:
a = res.split('+')[0]
b = res.split('+')[1]
zhi = int(a) + int(b)
if '-' in res:
a = res.split('-')[0]
b = res.split('-')[1]
zhi = int(a) - int(b)
if 'x' in res:
a = res.split('x')[0]
b = res.split('x')[1]
zhi = int(a) * int(b)
if '/' in res:
a = res.split('/')[0]
b = res.split('/')[1]
zhi = int(a) / int(b)
if '÷' in res:
a = res.split('÷')[0]
b = res.split('÷')[1]
zhi = int(a) / int(b)
if '*' in res:
a = res.split('*')[0]
b = res.split('*')[1]
zhi = int(a) * int(b)
return {"solution_result": zhi,
"raw_result": res
}
if __name__ == '__main__':
# swagger地址:http://localhost:6688/docs
uvicorn.run(app, port=6688, host="0.0.0.0")
直接啟動(dòng)main函數(shù),即可開始識(shí)別操作。
項(xiàng)目可以部署到服務(wù)器上,這樣就只用搭建一次,隨處調(diào)用
(此處因篇幅問題,只列舉了字符和算數(shù)識(shí)別的代碼。若需要滑塊,點(diǎn)選等代碼可以私聊作者)
效果測(cè)試
本次我用的是java來測(cè)試,模擬在爬蟲時(shí)遇到的某網(wǎng)站圖片驗(yàn)證碼識(shí)別。
測(cè)試代碼:
public static void main(String[] args) {
String validateUrl = "http://127.0.0.1:6688/code";//python項(xiàng)目啟動(dòng)的端口和路徑
String codeUrl = "*****" //該地址為圖片驗(yàn)證碼路徑,此處不做展示,請(qǐng)自行尋找測(cè)試;
String localSavePath = "D://codeTest.jpg";
saveImage(codeUrl, localSavePath);
String imgBase64 = GetImageStr(localSavePath);
JSONObject requestBody = new JSONObject();
requestBody.put("ImageBase64", imgBase64);
System.out.println(MyUtils.sendPost(validateUrl, requestBody.toJSONString(), null));
}
/**
* 保存接口響應(yīng)圖片
*
* @param codeRul :驗(yàn)證碼接口地址
* @param savePath :本地保存地址
*/
public static void saveImage(String codeRul, String savePath) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(codeRul).get().build();
// 將字節(jié)數(shù)組轉(zhuǎn)化為流
InputStream inputStream = client.newCall(request).execute().body().byteStream();
OutputStream os = null;
// 100K的數(shù)據(jù)緩沖
byte[] bs = new byte[102400];
// 讀取到的數(shù)據(jù)長(zhǎng)度
int len;
// 保存圖片
os = new FileOutputStream(savePath);
// 開始讀取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
System.out.println("保存失敗");
e.printStackTrace();
}
}
/**
* 圖片轉(zhuǎn)化成base64字符串
*
* @param imgPath :圖片絕對(duì)路徑
* @return base64字符串
*/
public static String GetImageStr(String imgPath) {// 將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對(duì)其進(jìn)行Base64編碼處理
String imgFile = imgPath;// 待處理的圖片
InputStream in = null;
byte[] data = null;
String encode = null; // 返回Base64編碼過的字節(jié)數(shù)組字符串
// 對(duì)字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
try {
// 讀取圖片字節(jié)數(shù)組
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
}
return encode;
}
運(yùn)行結(jié)果:
可以看出,即使是有干擾的圖片,該接口也可以迅速且準(zhǔn)確的識(shí)別出來。文章來源:http://www.zghlxwxcb.cn/news/detail-689606.html
覺得本文對(duì)您有幫助的話,請(qǐng)動(dòng)動(dòng)發(fā)財(cái)?shù)男∈贮c(diǎn)個(gè)贊支持~文章來源地址http://www.zghlxwxcb.cn/news/detail-689606.html
到了這里,關(guān)于python | 傻瓜式一鍵搭建圖片驗(yàn)證碼識(shí)別接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!