Python 이미지 소켓통신

paragon의 이미지

이번 새롭게 가입한 Paragon입니다.

이미지관련해서 관심이 많아 다음과 같은 프로젝트를 하고 있습니다.
Pi(client)에서 PC(server)로 이미지 + 문자(예를 들어 날짜)를 동시에 받아 sqlite에 저장이 가능하도록 하고 있습니다.
일단 시험삼아 노트북 내에서 노트북에 내장되어 있는 카메라를 연결해서 이미지를 캡처를 하고 임의 데이터 3개를 붙여서 서버에 전송은 가능한데, 받은 후 split(',')해서 분리하는 작업이 오류가 납니다.

제가 잘못하고 있는 부분이나, 조언을 듣고 싶습니다.

# server #
 
...
class EchoRequestHandler(socketserver.BaseRequestHandler):
    # Called before the handle()  method to perform any initialization actions required.
    def setup(self):
        print (self.client_address[0], 'connected!!')
 
    def handle(self):
        try:
            la_con.configure(text="Connecting...", foreground="red")
 
            data = None
 
            while (True):
                c_data = self.request.recv(1024)
                print(c_data)
 
        except:
            la_con.configure(text="Disconnecting...",foreground="black")
            messagebox.showerror("Erorr", "connecting Failed")
            print(self.client_address[0], 'disconnected!!')
    def finish(self):
        self.request.close()
 
class SocksServer(socketserver.ThreadingTCPServer):
    def __init__(self, listen_addr):
        socketserver.ThreadingTCPServer.__init__(self, listen_addr, EchoRequestHandler)
        # Whether the server will allow the reuse of an address.
        self.allow_reuse_address = True
        #
        self.daemon_threads = True
        # request_queue_size
        self.request_queue_size = 50
 
    def stop(self):
        self.shutdown()
 
    def start(self):
        self.serve_forever()
 
def clean_up_data(stringdata):
    stringdata.split(",")
    print(stringdata)
 
 
 
def insert_data(in_data1, in_data2, in_data3, in_data4, in_data5, in_data6, in_data7):
    con, cur = None, None
 
    # Image,sensor1,sensor2,sensor3,sensor4,sensor5,date
    data1, data2, data3, data4, data5, data6, data7 = "", "", "", "", "", "", ""
    sql = ""
 
    con = sqlite3.connect("D:/PyProgram/Cvproject/userDB")  # DB에 연결
    cur = con.cursor()
    cur.execute("SELECT * FROM datatable")  # 저장된 DB 출력
 
    data1 = in_data1
    data2 = in_data2
    data3 = in_data3
    data4 = in_data4
    data5 = in_data5
    data6 = in_data6
    data7 = in_data7
 
 
    sql = "INSERT INTO dataTable VALUES('" + data1 + "','"+ data2 + "','" + data3 + "'," + data4+ "'," + data5 + "'," + data6 + "'," + data7 + ")"
    cur.execute(sql)
 
    con.commit()  # DB에 저장
    con.close()  # DB 종료
 
 
def runserve(host,port):
    ser = SocksServer((host, port)).start()
 
def DataDB():
    subprocess.call(["python.exe",filist])
def close():
    plt.close(fig)
    server.destroy()
...

# client #
import socket
import time
import cv2
import numpy as np
 
def image():
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
 
    w = cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
    h = cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 320)
 
    frame_size = (int(cap.get(w)), int(cap.get(h)))
    ret, frame = cap.read()
 
    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
    jpg = cv2.imencode('.png', frame, encode_param)[1].tostring()
    data = str(len(jpg)).ljust(16)
 
    sampledata = str(jpg) + "," + str(60) + "," + str(20) + "," + data
    return sampledata
 
def sending():
 
    now = time.localtime()
    data7=("%04d-%02d-%02d %02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min))
    return data7
 
def run(host, port):
    c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    c.connect((host,port))
 
    data = image()
    while(True):
        c.sendall(data.encode())
        if data == None:
            break
    c.close()
 
 
if __name__ == '__main__':
    run('192.168.0.16',9999)

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.