python django工程上傳一張照片調(diào)用python方法時報錯,請問如何處理?
問題描述
python django工程上傳一張照片調(diào)用python方法時報錯,請問如何處理?工程目錄為:
代碼為:urls.py代碼為:
# -*- coding:utf-8 -*-'''face URL ConfigurationThe `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 urlfrom django.contrib import adminfrom jango import viewsurlpatterns = [#路由 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='關(guān)鍵詞,關(guān)鍵詞'><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:;' onclick='openBrows();'>上傳照片</a> <input type='file' name='file' onchange='saveFile();'/> <input type='text' /></form><!--end upload--><!--photo start--><p class='photo'> <p class='p_box'><img src='http://www.aoyou183.cn/wenda/{{ imgurl }}' alt='圖片' /><p class='bs scale'></p> </p> <p class='p_value'><h2>人臉識別掃描結(jié)果:</h2><p id='p_message'></p> </p></p><!--end photo--><script type='text/javascript' src='http://www.aoyou183.cn/wenda/static/js/jquery-1.11.1.min.js'></script><script type='text/javascript'> // 點(diǎn)擊按鈕,瀏覽本地圖片 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代碼對應(yīng)的頁面效果:
views.py代碼為:
# -*- coding:utf-8 -*-from django.shortcuts import renderfrom django.http import HttpResponseimport timeimport findfacedef 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) passelse: 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’})#首頁照片的默認(rèn)值,如果不需要則第三個參數(shù)可以不寫#return render(request,’face.html’)#首頁照片的默認(rèn)值,如果不需要則第三個參數(shù)可以不寫
findface.py代碼為:
# -*- coding: UTF-8 -*-import numpy as npimport timeimport cv2def find(img_pic): face_cascade = cv2.CascadeClassifier(’haarcascade_frontalface_default.xml’) face_cascade.load(r’E:OpenCV 2.4.9opencvsourcesdatahaarcascadeshaarcascade_frontalface_default.xml’)#不加這一行報錯 eye_cascade = cv2.CascadeClassifier(’haarcascade_eye.xml’) eye_cascade.load(r’E:OpenCV 2.4.9opencvsourcesdatahaarcascadeshaarcascade_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點(diǎn)擊“上傳照片”,想要傳遞一張照片guofu.jpg,并調(diào)用findface.py的find方法顯示人的面部,并用方框?qū)⑷说拿娌坷ㄆ饋恚浅霈F(xiàn)下圖的錯誤,請問如何解決?
問題解答
回答1:face_cascade.load(r’E:OpenCV 2.4.9opencvsourcesdatahaarcascadeshaarcascade_frontalface_default.xml’)#不加這一行報錯 eye_cascade = cv2.CascadeClassifier(’haarcascade_eye.xml’) eye_cascade.load(r’E:OpenCV 2.4.9opencvsourcesdatahaarcascadeshaarcascade_eye.xml’)回答2:
你的路徑調(diào)用出錯,導(dǎo)致opencv無法正確的讀取圖像文件,這是你提問的答案。在views.py內(nèi)將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文檔上的東西直接復(fù)制下來了,不理解的話沒什么用。這只是改了其中的一個地方,你的程序錯誤很多。第一、你把圖像上傳和處理的函數(shù)寫在一個方法內(nèi),這時候沒法知道圖像什么時候處理好,你需要把圖像處理函數(shù)分開寫或者使用多線程的方法進(jìn)行改寫第二、Django在使用ajax方法進(jìn)行post操作時需要進(jìn)行csrf驗(yàn)證,如果沒有程序是無法運(yùn)行的第三、你的js寫的有問題,只要加載頁面就執(zhí)行post操作,你自己再看一下還有一些細(xì)節(jié)方面的東西,多注意一下
相關(guān)文章:
