Files
webp/bin/resnet.py
2023-11-17 01:12:22 +08:00

57 lines
2.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import towhee
from http.server import BaseHTTPRequestHandler, HTTPServer
img_path = './data/test.jpeg'
feat = towhee.glob(img_path).image_decode().image_embedding.timm(model_name='resnet50').tensor_normalize().to_list()
print(feat[0])
# 定義一個服務器類
class ResNetServer(BaseHTTPRequestHandler):
# 定義一個初始化方法
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 定義一個處理 GET 請求的方法
def do_GET(self):
self.send_response(200) # 設置服務器響應的狀態碼
self.send_header('Content-type', 'text/html') # 設置服務器響應的標頭
self.end_headers() # 完成服務器響應的標頭
# 設置服務器響應的內容
self.wfile.write(bytes('''
<html>
<head>
<meta charset="utf-8">
<title>ResNet Server</title>
</head>
<body>
<h1>ResNet Server</h1>
// 這裡是一個簡單的服務器可以接收圖像文件並將圖像文件轉換為ResNet50的特徵向量
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
<p>Upload an image to get the prediction result.</p>
// 發送JSON格式的表單
</body>
</html>
''', 'utf-8'))
# 定義一個處理 POST 請求的方法, 接收二進制圖像文件
def do_POST(self):
self.send_response(200) # 設置服務器響應的狀態碼
self.send_header('Content-type', 'application/json') # 設置服務器響應的標頭
self.end_headers() # 完成服務器響應的標頭
content_length = int(self.headers['Content-Length']) # 獲取請求的內容長度
body = self.rfile.read(content_length) # 獲取請求的內容
feat = towhee.blob(body).image_decode().image_embedding.timm(model_name='resnet50').tensor_normalize().to_list()
results = json.dumps(feat[0].tolist()) # 將結果轉換為JSON格式
self.wfile.write(bytes(results, 'utf-8')) # 將結果發送給客戶端
# 判斷是否是直接執行該文件
if __name__ == '__main__':
HTTPServer(('0.0.0.0', 8000), ResNetServer).serve_forever()