加入图片相似度功能
getpic进行网络图片保存在本地
# -*- coding: utf-8 -*-
import os
import uuid
from PIL import Image
import requests
from io import BytesIO# 对图片进行统一化处理
def get_thum(image, size=(64, 64), greyscale=False):if image is None:raise ValueError("Cannot process None image")image = image.resize(size, Image.ANTIALIAS)if greyscale:image = image.convert('L')return imagedef getpic(image_url):random_filename = str(uuid.uuid4()) + '.jpg'try:response = requests.get(image_url)if response.status_code == 200:image_content = response.contentimage_stream = BytesIO(image_content)image = Image.open(image_stream)save_path = random_filenameimage.save(save_path)print(f'图片已保存到:{os.path.abspath(save_path)}')# 这里应该返回 Image 对象,而不是文件路径# 但是由于我们稍后要关闭文件,所以返回文件路径,并在需要时重新打开return save_pathelse:print('无法获取图片,服务器响应码:', response.status_code)except requests.exceptions.InvalidURL as e:print(f"Invalid URL: {e}")except requests.exceptions.RequestException as e:print(f"An error occurred while making the request: {e}")# 计算图片的余弦距离(实际上计算的是余弦相似度)def similarity_pics(image_path1, image_path2):# 打开图像文件并获取 Image 对象image1 = Image.open(image_path1).convert('L')image2 = Image.open(image_path2).convert('L')# 确保图像是相同的大小和模式(例如,都是 RGB 或都是 L(灰度))# 这里我们假设图像已经是相同的大小,因为它们都经过了 get_thum 的处理# 将图像转换为向量# 注意:这里的实现方式可能需要更改,因为直接将像素值平均可能不是最佳方式# 通常,您可能会将图像转换为特征向量,使用例如 SIFT、SURF 或其他图像特征提取方法vectors = [list(map(int, image1.getdata())), list(map(int, image2.getdata()))]# 计算向量的余弦相似度a, b = vectorsa_norm = sum([x ** 2 for x in a]) ** 0.5b_norm = sum([x ** 2 for x in b]) ** 0.5dot_product = sum(a_i * b_i for a_i, b_i in zip(a, b))similarity = dot_product / (a_norm * b_norm)return similarity
接口代码:
import os
import uvicorn
from fastapi import FastAPI, Form
from twopics import similarity_pics, getpic
app = FastAPI()@app.get("/")
async def index():"""注册一个根路径:return:"""return {"message": "自定义请求"}@app.post("/")
async def login(pic1: str = Form(...), pic2: str = Form(...)):image1 = getpic(pic1)image2 = getpic(pic2)re = similarity_pics(image1, image2)os.remove(image1)os.remove(image2)return {"re": re,"brief":'图片相似度'}@app.get("/about")
async def about():"""项目信息:return:"""return {"app_name": "人工智能识别","app_version": "v0.0.1"}if __name__ == "__main__":uvicorn.run(app, host="127.0.0.1", port=8222)