60 lines
2.9 KiB
Python
60 lines
2.9 KiB
Python
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) # 獲取請求的內容
|
||
#img_path = './data/' + str(uuid.uuid4()) # 生成一個隨機的圖像文件名
|
||
#with open(img_path, 'wb') as f: # 將二進制圖像文件解碼為圖像數據保存在本地
|
||
# f.write(body)
|
||
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()
|