将 std::vector<uchar> buff 转换为 const char*

问题描述 投票:0回答:1

大家好,我需要将

std::vector<uchar>
转换为
const char*
或在 Windows 系统中使用
std::vector<uchar>
通过套接字发送
winsock2.h

我该怎么做?

我正在压缩一张图像:

std::vector<uchar> buff;//buffer for coding
std::vector<int> param(2);
param[0] = cv::IMWRITE_JPEG_QUALITY;
param[1] = 40;//default(95) 0-100

cv::imencode(".jpeg", frame, buff, param);

然后:

我需要通过套接字发送

std::vector<uchar> buff
,但
send()
只接受
const char*

我有两个程序,客户端和服务器,我想使用 JPG 缓冲区通过套接字发送图像,以供服务器接收并转换回 OpenCV mat。

我已经这样做了,但没有成功:

int bytes = 0;

if (!imgMat.empty())                
    {
    if ((bytes = send(server, (const char*)buff.data() , buff.size(),   0)) < 0)   //if  ((bytes = send(server, (char*)imgMat.data, imageSize, 0)) < 0) 
    {
         ::cout << "Error while sending..";
         break;
    }
    ::cout << "Frame sent sucessfuly" << endl;
        ::cout << bytes << " bytes sent." << endl;
 }
else
 {
    ::cout << "Frame was empty" << endl;
    break;
 }

目的是通过占用更少空间的图像来提高发送速度。

c++ opencv vector winsock2 unsigned-char
1个回答
0
投票

在接收端,您需要将

sizeof(buff.data())
更改为
buff.size()
。并且,您需要预先调整
buff
的大小,然后才能将其与
recv()
一起使用。这意味着您需要知道发送方期望发送多少字节。因此发送方应该发送其缓冲区大小及其实际缓冲区数据。

尝试更多类似这样的事情:

发件人:

bool sendall(SOCKET sock, const void *data, uint32_t size)
{
    const char *ptr = static_cast<const char*>(data);
    while (size > 0)
    {
        int bytes = send(sock, ptr, static_cast<int>(size), 0);
        if (bytes < 0) return false;
        ptr += bytes;
        size -= bytes;
    }
    return true;
}

...

std::vector<uchar> buff;
std::vector<int> param(2);
param[0] = cv::IMWRITE_JPEG_QUALITY;
param[1] = 40;//default(95) 0-100

cv::imencode(".jpeg", frame, buff, param);

if (buff.empty())
{
    ::cout << "Frame was empty" << endl;
    break;
}

uint32_t size = buff.size();

if (!(sendall(server, &size, sizeof(size)) &&
      sendall(server, buff.data(), size)))
{
    ::cout << "Error while sending..";
    break;
}

::cout << "Frame sent successfully" << endl;
::cout << size << " bytes sent." << endl;

接收者:

bool recvall(SOCKET sock, void *data, uint32_t size)
{
    char *ptr = static_cast<char*>(data);
    while (size > 0)
    {
        int bytes = recv(sock, ptr, static_cast<int>(size), MSG_WAITALL);
        if (bytes < 0) return false;
        ptr += bytes;
        size -= bytes;
    }
    return true;
}

...

uint32_t size;
if (!recvall(client, &size, sizeof(size)))
{
    cout << "Error while recv frame" << endl;
    break;
}

std::vector<uchar> buff(size);
if (!recvall(client, buff.data(), size))
{
    cout << "Error while recv frame" << endl;
    break;
}

cv::Mat imgMat = cv::imdecode(Mat(buff), IMREAD_COLOR);
cv::imshow("Client screen seen from the Server", imgMat);
cv::waitKey(1);
© www.soinside.com 2019 - 2024. All rights reserved.