[Python] How to send and recieve a cv2 image in the form of numpy array

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm an intermediate in python and new to libraries like numpy and opencv. I'm trying to make a video calling app using sockets.This code is just a try. I've tried in the following way but as it receives the array it's size becomes 0 and shape becomes null. Please help me do this. I'm sorry for anymistakes I've done

    any help will be appreciated

    Thank you. Have a nice day enter

    Server:-

    import socket
    import threading
    from _thread import *
    import cv2
    import numpy as np

    srvr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_ip = socket.gethostbyname(socket.gethostname())
    port = 9999
    client = []
    try:
    srvr.bind((server_ip, port))
    except socket.error as e:
    print(e)



    def connected_client(conn, addr):
    global client
    print("[SERVER]: CONNECTED WITH ", addr)
    check_msg = "Welcome Client"
    conn.send(str.encode(check_msg))
    while True:
    try:
    data = conn.recv(5000)
    if not data:
    print("[SERVER]: DISCONNECTED..")
    break
    for i in client:
    i.sendall(data)
    except:
    break

    conn.close()


    srvr.listen(5)
    while True:
    print("[SERVER]: STARTED...\n [SERVER]: ACCEPTING CONNECTIONS....")
    conn, addr = srvr.accept()
    start_new_thread(connected_client, (conn, addr))
    client.append(conn)



    Client:-

    import socket, cv2
    import threading
    from _thread import *
    import numpy as np
    import time
    import base64

    video = cv2.VideoCapture(0)

    clt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    SERVER = socket.gethostbyname(socket.gethostname())
    PORT = 9999
    ADDR = (SERVER, PORT)

    clt.connect(ADDR)
    print(clt.recv(2048).decode())
    #recieving data from server
    def recieve():
    global clt
    while True:
    recv_frame = clt.recv(5000)
    nparr = np.frombuffer(recv_frame, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    key = cv2.waitKey(1)
    if key == ord('a'):
    break
    print(img)
    # cv2.imshow("aman", recv_frame)

    # break
    # https://stackoverflow.com/questions/17967320/python-opencv-convert-image-to-byte-string

    # new thread while to continuously recieve data
    start_new_thread(recieve, ())

    # loop for continuously sending data
    while True:
    check, frame = video.read()
    str_frame = cv2.imencode('.jpg', frame)[1].tobytes()
    clt.sendall(str_frame)


    video.release()
    cv2.destroyAllWindows()

    Continue reading...

Compartilhe esta Página