我试图创建一个函数,可以检测到每篇文章的图像的颜色,但我很难使其正常工作。Django图像颜色检测功能不叫
这里是我的代码
views.py
from collections import defaultdict
from PIL import Image
def article(request):
context = {'article': Article.objects.all()}
return render(request, 'article.html', context)
def color_detection(request):
article = get_object_or_404(Article, None)
image = article.image
my_image = Image.open(image)
by_color = defaultdict(int)
for pixel in my_image.getdata():
by_color[pixel] += 1
total = 0
for key, x in by_color.items(): #taking the elements of dict
a = [i for i in key] #turning them into multiple lists
if total <= 1: #taking the first list of the list of lists
tuple_of_a = tuple(a)
print(tuple_of_a) #should return the color of one colored pixel of the image something like (r, g, b)
context = {'color':tuple_of_a}
total += 1
else:
break
return render(request, 'article.html', context)
[... other unrelated views ...]
urls.py
urlpatterns = [
url(r'^$', views.article, name="index"),
url(r'^$', views.color_detection, name='color_detection'),
[... unrelated urls ...]
]
template.py
{% for a in article %}
[... unrelated html ...]
<p>{{ a.color }}</p>
{% endfor %}
这是我在django作为初学者的第一个项目,所以我的错误可能是基本的,但我不明白为什么不调用color_detection()函数,如果你看到代码中的其他错误,指出,它会非常有帮助。
有什么想法/建议吗?
谢谢你,我很困惑意见和模型。没有理解我的操作在哪里。 – Lindow