Django后端编辑图片提取主要颜色API
生活随笔
收集整理的這篇文章主要介紹了
Django后端编辑图片提取主要颜色API
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、需求
前端頁(yè)面需要調(diào)用后端API,實(shí)現(xiàn)獲取主要顏色json數(shù)據(jù)
二、圖片效果
三、代碼實(shí)現(xiàn):
# Create your views here. import os from django.core.files.storage import default_storage from django.http import HttpResponse, JsonResponse from PIL import Image from webcolors import rgb_to_hexdef test_url(request):"""測(cè)試接口"""return HttpResponse("hello world")def palette(req):colors = {}# 判斷接收方式if req.method == 'POST':# 獲取圖片first_image = req.FILES.get("image", None)# 保存圖片image_path = os.path.join('static/', 'image.jpg')default_storage.save(image_path, first_image)# 提取圖片主要的十種顏色image = Image.open(image_path)small_image = image.resize((80, 80))# 圖片的主要十種顏色result = small_image.convert("P", palette=Image.ADAPTIVE, colors=10)# 提取顏色palette = result.getpalette()color_counts = sorted(result.getcolors(), reverse=True)col_sum = sum([i[0] for i in color_counts])for i in range(len(color_counts)):palette_index = color_counts[i][1]ratio = color_counts[i][0] / col_sumdominant_color = palette[palette_index * 3: palette_index * 3 + 3]# rgb轉(zhuǎn)化為二進(jìn)制color_str = rgb_to_hex(dominant_color[:3])# key為顏色,值為所占圖片的比例colors[str(color_str)] = ratio# 刪除圖片os.remove(image_path)return JsonResponse({"error": 0,"message": "no error","result": {"colors": colors}})else:return JsonResponse({"error": 1,"message": "method error","result": {}})四、返回JSON數(shù)據(jù)
{"error": 0,"message": "no error","result": {"colors": {"#f5f5f5": 0.2359375,"#685648": 0.13578125,"#423933": 0.13109375,"#1f2528": 0.12265625,"#a38970": 0.11890625,"#e5dedc": 0.11421875,"#f9f8f9": 0.06,"#f5f5f4": 0.04625,"#f4f5f5": 0.02703125,"#f9f5f6": 0.008125}} }?
總結(jié)
以上是生活随笔為你收集整理的Django后端编辑图片提取主要颜色API的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python中的iter()函数与nex
- 下一篇: 机器学习回归算法—岭回归及案例分析