图像在本地主机上显示已损坏

Image shows up corrupted on localhost

本文关键字:显示 已损坏 主机 图像      更新时间:2023-10-16

我对 c++ 和编程非常陌生。我只是尝试使用 opencv 读取图片并使用 boost asio 将其显示在 Web 服务器上。这是我对视频中的所有帧执行此操作之前的第一步。这是我的代码——

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <thread>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
using boost::asio::ip::tcp;
using namespace std;
using namespace cv;
int main(){
try{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 1112));
for (;;){
tcp::socket socket(io_service);
acceptor.accept(socket);
boost::system::error_code ignored_error;
cv::Mat frame = cv::imread("x.jpg");
vector<uchar> buff;
vector<int> param = vector<int>(2);
param[0]=cv::IMWRITE_JPEG_QUALITY;
param[1]=95;
imencode(".jpg",frame,buff,param);
const char mess[] = "axaxaxaxasaaaaaaaaaaxax";
std::string content(buff.begin(), buff.end());
boost::asio::write(socket, boost::asio::buffer(content), boost::asio::transfer_all(), ignored_error);
// boost::asio::write(socket, boost::asio::buffer(mess), boost::asio::transfer_all(), ignored_error);
}
}
catch(std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}

现在发送消息工作正常,但是当我尝试通过内容或buff发送图像时,它显示为胡言乱语。我觉得这是因为我在发送图片之前没有发送有关图片的任何信息。但是我不知道该怎么做。 或者也许我完全错了。任何帮助/建议将不胜感激。干杯!

我稍微简化了代码:

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <opencv2/opencv.hpp>
using boost::asio::ip::tcp;
int main(){
try{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 1112));
for (;;){
tcp::socket socket(io_service);
acceptor.accept(socket);
cv::Mat frame = cv::imread("x.jpg");
std::vector<uchar> buff;
imencode(".jpg", frame, buff, std::vector<int> { cv::IMWRITE_JPEG_QUALITY, 95 });
boost::system::error_code err;
auto bytes_transferred = boost::asio::write(socket, boost::asio::buffer(buff), boost::asio::transfer_all(), err);
std::cout << "Written: " << bytes_transferred << " (" << err.message() << ")n";
}
}
catch(std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}

(具体来说,不要不必要地使用using namespace,不要不必要地复制到 std::string 中,不要不必要地忽略错误代码(

编译它

g++ test.cpp -L/usr/local/lib -pedantic -Wall -Wextra -pthread -lope^Cv_{core,imgproc,imgcodecs} -lboost_{system,thread} -o test.exe

将 sampe jpeg 复制为 x.jpg,在终端中运行它:

./test.exe

然后使用netcat读取结果:

netcat localhost 1112 > verify.jpg

服务器进程每次都会打印相同的消息:

Written: 6130 (Success)

(6130 字节恰好是我选择的测试图像的 95% 重新编码大小(。生成的图像(验证.jpg(在我的图像查看器中看起来不错。

结论

我认为代码可能很好(但请检查上面的改进(,您可能错误地测试结果。