Rumah > Soal Jawab > teks badan
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-->
<p class="banner"></p>
<!--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-->
<p class="photo">
<p class="p_box">
<img src="{{ imgurl }}" id="path" alt="图片" width="505" />
<p class="bs scale"></p>
</p>
<p class="p_value">
<h2>人脸识别扫描结果:</h2>
<p class="p_info" id="p_message">
</p>
</p>
</p>
<!--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方法显示人的面部,并用方框将人的面部括起来,但是出现下图的错误,请问如何解决?
大家讲道理2017-04-18 10:30:39
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')
天蓬老师2017-04-18 10:30:39
Ralat panggilan laluan anda menyebabkan opencv tidak dapat membaca fail imej dengan betul. Ini adalah jawapan kepada soalan anda.
Tukar b = str(a)+".jpg"
kepada b = 'jango/'+path
dalam views.py,
tukar pembolehubah laluan facefind kepada
import cv2
def 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()
Anda hanya menyalin bahan daripada dokumen opencv secara langsung. Tidak berguna jika anda tidak memahaminya. Ini hanyalah salah satu perubahan, program anda mempunyai banyak ralat.
Pertama, anda menulis fungsi muat naik dan pemprosesan imej dalam satu kaedah Pada masa ini, tiada cara untuk mengetahui bila imej diproses secara berasingan atau menggunakan kaedah berbilang benang tulis semula
Kedua, Django perlu melakukan pengesahan csrf apabila menggunakan kaedah ajax untuk operasi pos Jika tiada program, ia tidak boleh dijalankan
Ketiga, terdapat sesuatu yang salah dengan penulisan js anda sedang dimuatkan, operasi pos akan dilakukan Anda boleh menyemaknya sendiri Di sini
terdapat beberapa butiran, sila beri perhatian lebih