大家好,我需要将
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;
}
目的是通过占用更少空间的图像来提高发送速度。
在接收端,您需要将
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
if (!cv::imencode(".jpeg", frame, buff, param))
{
std::cout << "Error encoding frame" << std::endl;
break;
}
uint32_t size = buff.size();
if (!(sendall(server, &size, sizeof(size)) &&
sendall(server, buff.data(), size)))
{
std::cout << "Error sending frame" << std::endl;
break;
}
std::cout << "Frame sent successfully" << std::endl;
std::cout << size << " bytes sent" << std::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), 0);
if (bytes <= 0) return false;
ptr += bytes;
size -= bytes;
}
return true;
*/
return (recv(sock, static_cast<char*>(data), static_cast<int>(size), MSG_WAITALL) > 0);
}
...
uint32_t size;
if (!recvall(client, &size, sizeof(size)))
{
std::cout << "Error while receiving frame" << std::endl;
break;
}
std::vector<uchar> buff(size);
if (!recvall(client, buff.data(), size))
{
std::cout << "Error while receiving frame" << std::endl;
break;
}
cv::Mat imgMat = cv::imdecode(Mat(buff), IMREAD_COLOR);
cv::imshow("Client screen seen from the Server", imgMat);
cv::waitKey(1);