python django工程上传一张照片调用python方法时报错,请问如何处理?
python django工程上传一张照片调用python方法时报错,请问如何处理?
工程目录为:
代码为:
urls.py代码为:
# -*- coding:utf-8 -*-"""face URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from jango import views
urlpatterns = [#路由
url(r'^admin/', admin.site.urls),
url(r'^$',views.index)
]
html代码为:
<!doctype html><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta name="keywords" content="关键词,关键词">
<meta name="description" content="">
<style type="text/css">
*{margin:0;padding:0;}
body{background:#E6E6E6;font-size:12px;font-family:"微软雅黑";color:#666;}
/*h1 start*/
h1{line-height:80px;text-align:center;font-weight:300;color:#000000;}
/*end h1*/
/*banner start*/
.banner{width:100%;height:230px;background:url("static/images/banner.jpg") top center;background-repeat:no-repeat}
/*end banner*/
/*upload start*/
.upload{width:180px;height:36px;display:block;margin:30px auto;text-align:center;line-height:36px;text-decoration:none;font-size:16px;border-radius:20px;border:1px solid #00b4ff;color:#00b4ff;}
.upload:hover{background:#00b4ff;color:#ffffff;}
/*end upload*/
/*photo start*/
.photo{width:800px;height:460px;margin:0 auto;}
.photo .p_box{width:505px;height:460px;background:#ffcc99;float:left;position:relative;}
.photo .p_value{width:290px;height:460px;background:#ffffff;float:right;}
.photo .p_value h2{font-size:24px;font-weight:500;text-align:center;line-height:120px;}
.photo .p_value .p_info{font-size:16px;padding-left:35px;line-height:50px;}
/*end photo*/
@-webkit-keyframes renlian {
from {height: 5px;}
10% {height: 50px;}
40% {height: 100px;}
50% {height: 150px;
}
60% {
height: 250px;
}
80% {
height: 460px;
}
60% {
height: 250px;
}
50% {
height: 150px;
}
40% {
height: 100px;
}
10% {
height: 50px;
}
to {
height: 0px;
}
}
.scale {animation: renlian 1.5s infinite ease;-webkit-animation: renlian 1.5s infinite ease;}
.bs {position: absolute;background: green;width: 505px;height: 460px;top: 0px;left: 0px;font-size:36px;text-align:center;line-height:400px;color:#fff;opacity: 0.3}
#file,#filename{display:none;}
</style>
</head>
<body>
<!--h1 start-->
<h1></h1>
<!--end h1-->
<!--banner start-->
<div class="banner"></div>
<!--end banner-->
<!--upload start-->
<form action="/" method="post" enctype="multipart/form-data" id="arryForm">
<a href="javascript:;" class="upload" onclick="openBrows();">上传照片</a>
<input type="file" id="file" name="file" onchange="saveFile();"/>
<input type="text" id="filename" />
</form>
<!--end upload-->
<!--photo start-->
<div class="photo">
<div class="p_box">
<img src="{{ imgurl }}" id="path" alt="图片" width="505" />
<div class="bs scale"></div>
</div>
<div class="p_value">
<h2>人脸识别扫描结果:</h2>
<p class="p_info" id="p_message">
</p>
</div>
</div>
<!--end photo-->
<script type="text/javascript" src="static/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
// 点击按钮,浏览本地图片
function openBrows(){
var ie = navigator.appName == "Microsoft Internet Explorer" ? true:false;
if(ie){
document.getElementById("file").click();
document.getElementById("filename").value = document.getElementById("file").value;
} else {
var a = document.createEvent("MouseEvents");
a.initEvent("click",true,true);
document.getElementById("file").dispatchEvent(a);
}
}
// 提交表单
function saveFile(){
document.getElementById("arryForm").submit();
}
jQuery(function(){
faceDo();
});
function faceDo(){
var msg = jQuery("#path").attr("src");
jQuery.ajax({
type:"post",
url:"/",
data:{"path":msg},
success:function(data){
jQuery("#p_message").prepend(data);
jQuery(".bs").removeClass().empty();
}
});
}
</script>
</body>
</html>
html代码对应的页面效果:
views.py代码为:
# -*- coding:utf-8 -*-from django.shortcuts import render
from django.http import HttpResponse
import time
import findface
def index(request):
method = request.method
if method =='POST':
if request.POST.get('path'):
# faceinfo = face_api.getPicInfo('http://img.sccnn.com/bimg/337/47838.jpg')
# return HttpResponse(faceinfo)
pass
else:
img = request.FILES.get('file')#获取用户上传的文件(图片)
if not img:#img没有值
return HttpResponse(u'上传失败')
a = time.time()
path = 'static/faceimg/%s.jpg' %a
with open('jango/'+path,'wb') as fn:#w写字符串,wb写文件
fn.write(img.read())
print str(a)+".jpg"
b = str(a)+".jpg"
findface.find(b)
return render(request,'face.html',context={'imgurl':path})
else:
return render(request,'face.html',context={'imgurl':'http://img.sccnn.com/bimg/337/47838.jpg'})#首页照片的默认值,如果不需要则第三个参数可以不写
#return render(request,'face.html')#首页照片的默认值,如果不需要则第三个参数可以不写
findface.py代码为:
# -*- coding: UTF-8 -*-import numpy as np
import time
import cv2
def find(img_pic):
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_cascade.load(r'E:\OpenCV 2.4.9\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')#不加这一行报错
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
eye_cascade.load(r'E:\OpenCV 2.4.9\opencv\sources\data\haarcascades\haarcascade_eye.xml')#不加这一行报错
img = cv2.imread(img_pic)
path = 'static/faceimg/%s.jpg' % img_pic
with open('jango/' + path, 'wb') as fn: # w写字符串,wb写文件
fn.write(img.read())
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
在地址栏输入:http://localhost:8000/
点击“上传照片”,想要传递一张照片guofu.jpg,并调用findface.py的find方法显示人的面部,并用方框将人的面部括起来,但是出现下图的错误,请问如何解决?
回答:
face_cascade.load(r'E:\OpenCV 2.4.9\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')#不加这一行报错 eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
eye_cascade.load(r'E:\OpenCV 2.4.9\opencv\sources\data\haarcascades\haarcascade_eye.xml')
回答:
你的路径调用出错,导致opencv无法正确的读取图像文件,这是你提问的答案。
在views.py内将b = str(a)+".jpg"
改为b = 'jango/'+path
,
将facefind的path变量改为
import cv2def find(img_pic):
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_cascade.load('/usr/local/Cellar/opencv3/HEAD-4a095e4_4/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')#这是mac下的路径,改成你自己的
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
eye_cascade.load('/usr/local/Cellar/opencv3/HEAD-4a095e4_4/share/OpenCV/haarcascades/haarcascade_eye.xml')#不加这一行报错
img = cv2.imread(img_pic)
path = img_pic
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imwrite(path,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
你只是把opencv文档上的东西直接复制下来了,不理解的话没什么用。这只是改了其中的一个地方,你的程序错误很多。
第一、你把图像上传和处理的函数写在一个方法内,这时候没法知道图像什么时候处理好,你需要把图像处理函数分开写或者使用多线程的方法进行改写
第二、Django在使用ajax方法进行post操作时需要进行csrf验证,如果没有程序是无法运行的
第三、你的js写的有问题,只要加载页面就执行post操作,你自己再看一下
还有一些细节方面的东西,多注意一下
以上是 python django工程上传一张照片调用python方法时报错,请问如何处理? 的全部内容, 来源链接: utcz.com/a/158972.html