本文主要是介绍python服务程序(调用摄像头查看视频和识别二维码)+ Android 客户端程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
运行效果图
服务器端程序
#!/usr/bin/python
'''
服务器端程序 do_GET() 方法调用webcam摄像头,查看监控视频,同时识别二维码,do_POST()方法连接Mysql数据库,获取数据,并以webservice的形式发布出去供移动客户端与Mysql数据交互。
'''
import cv2
import Image
import threading
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from SocketServer import ThreadingMixIn
import StringIO
import time
import qrtools
import serial
import MySQLdb
import datetime
import cgi
import random
import stringcapture = None
qr = qrtools.QR()
sr = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1)
db = MySQLdb.connect('localhost', 'root', 'root', 'homedb')
cursor = db.cursor()def passwd_generator():s = string.ascii_letters + string.digitsl = len(s)passwd_l = 10return ''.join([s[random.randrange(0, l-1)] for x in range(passwd_l)])class CamHandler(BaseHTTPRequestHandler):def do_GET(self):if self.path.endswith('.mjpg'):self.send_response(200)self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')self.end_headers()while True:try:rc, img = capture.read()if not rc:continueimgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)jpg = Image.fromarray(imgRGB)tmpFile = StringIO.StringIO()jpg.save(tmpFile,'JPEG')if qr.decode(tmpFile):print(qr.data)''' Verify QR code '''username, passwd = qr.data.trim().split(',')cursor.execute('select * from user where username="' + qr.username + '"')data = cursor.fetchone()if not data:continued = datetime.datetime.now() - data[3]if d < datetime.delta(seconds=10):if passwd == data[2]:''' Open lock via arduino'''if sr.isOpen():sr.write(b'1')self.wfile.write("--jpgboundary")self.send_header('Content-type','image/jpeg')self.send_header('Content-length',str(tmpFile.len))self.end_headers()jpg.save(self.wfile,'JPEG')time.sleep(0.05)except KeyboardInterrupt:breakreturnif self.path.endswith('.html'):self.send_response(200)self.send_header('Content-type','text/html')self.end_headers()with open('front.html', 'r') as f:self.wfile.write(f.read());# self.wfile.write('<html><head></head><body>')self.wfile.write('<img class="img-responsive" src="http://192.168.1.201:8800/cam.mjpg"/>')# self.wfile.write('</body></html>')with open('end.html', 'r') as f:self.wfile.write(f.read())returndef do_POST(self):if self.path == '/authenticate':ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))if ctype == 'multipart/form-data':postvars = cgi.parse_multipart(self.rfile, pdict)elif ctype == 'application/x-www-form-urlencoded':length = int(self.headers.getheader('content-length'))postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)else:postvars = {}if postvars:username = postvars['username'][0]print("username=" + username)cursor.execute('select * from user where username=%s', (username, ))d = cursor.fetchone()if d:new_passwd = passwd_generator()print("new passwd=" + new_passwd)# cursor.execute('select * from user')cursor.execute('update user set passwd=%s, last_update=%s where username=%s', (new_passwd, datetime.datetime.now(), username))db.commit()if cursor:self.send_response(200)self.end_headers()self.wfile.write(username + ',' + new_passwd)print("response OK!")returnelse:self.send_response(200)self.send_header('Content-type', 'text/html')self.end_headers()self.wfile.write('<htm><body>Hello world</body></html>')returnclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):"""Handle requests in a separate thread."""def main():global captureglobal qrglobal srglobal cursorcapture = cv2.VideoCapture(0)capture.set(cv2.CAP_PROP_FRAME_WIDTH, 960);capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 544);capture.set(cv2.CAP_PROP_SATURATION,0.2);global imgtry:server = ThreadedHTTPServer(('192.168.1.201', 8800), CamHandler)print "server started"server.serve_forever()except KeyboardInterrupt:capture.release()server.socket.close()cursor.close()db.close()if __name__ == '__main__':main()
Android 手机客户端程序
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.example.king.httppostdemo.MainActivity"android:orientation="vertical"><Button
android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Click"android:id="@+id/button"android:layout_alignTop="@+id/text1"android:layout_alignParentLeft="true"android:layout_alignParentStart="true" /><TextView
android:id="@+id/text1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!" />
</LinearLayout>
MainActivity.java
package com.example.king.httppostdemo;import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;import java.util.HashMap;public class MainActivity extends Activity {private TextView tv1;private Button bt;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv1=(TextView)findViewById(R.id.text1);bt=(Button)findViewById(R.id.button);bt.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {HashMap<String, String> data = new HashMap<String, String>();data.put("username", "hello");AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);asyncHttpPost.setListener(new AsyncHttpPost.Listener(){@Overridepublic void onResult(String result) {// do something, using return value from networktv1.setText(result);}});asyncHttpPost.execute("http://192.168.1.201:8800/authenticate");}});}}
asyncHttpPost.class
package com.example.king.httppostdemo;import android.os.AsyncTask;import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;/*** Created by king on 16-10-6.*/
class AsyncHttpPost extends AsyncTask<String, String, String> {interface Listener {void onResult(String result);}private Listener mListener;private HashMap<String, String> mData = null;// post data/*** constructor*/public AsyncHttpPost(HashMap<String, String> data) {mData = data;}public void setListener(Listener listener) {mListener = listener;}/*** background*/@Overrideprotected String doInBackground(String... params) {byte[] result = null;String str = "";HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URLtry {// set up post dataArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();Iterator<String> it = mData.keySet().iterator();while (it.hasNext()) {String key = it.next();nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));}post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));HttpResponse response = client.execute(post);StatusLine statusLine = response.getStatusLine();if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){result = EntityUtils.toByteArray(response.getEntity());str = new String(result, "UTF-8");}}catch (UnsupportedEncodingException e) {e.printStackTrace();}catch (Exception e) {}return str;}/*** on getting result*/@Overrideprotected void onPostExecute(String result) {// something...if (mListener != null) {mListener.onResult(result);}}
}
源码(click here)
这篇关于python服务程序(调用摄像头查看视频和识别二维码)+ Android 客户端程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!