added image compression to thread

This commit is contained in:
2025-01-22 13:32:43 +01:00
parent e262325565
commit 69eba455f9

View File

@@ -48,7 +48,7 @@ void setup()
int main() int main()
{ {
setup(); setup();
// std::thread image(CapnSend); std::thread image(CapnSend);
std::thread safety([&](){ robot.robotSafety(&message); }); std::thread safety([&](){ robot.robotSafety(&message); });
std::thread sendMqtt([&](){ sendKobukiData(robot.parser.data); }); std::thread sendMqtt([&](){ sendKobukiData(robot.parser.data); });
std::thread connectionChecker(checkKobukiConnection); std::thread connectionChecker(checkKobukiConnection);
@@ -66,7 +66,7 @@ int main()
sendMqtt.join(); sendMqtt.join();
safety.join(); safety.join();
// image.join(); image.join();
} }
std::mutex connectionMutex; std::mutex connectionMutex;
@@ -407,6 +407,7 @@ std::string serializeKobukiData(const TKobukiData &data)
json += "]}"; json += "]}";
return json; return json;
} }
// create extra function to send the message every 100ms // create extra function to send the message every 100ms
// needed it so it can be threaded // needed it so it can be threaded
void sendKobukiData(TKobukiData &data) void sendKobukiData(TKobukiData &data)
@@ -420,7 +421,8 @@ void sendKobukiData(TKobukiData &data)
} }
void CapnSend() { void CapnSend() {
VideoCapture cap(0); int COMPRESSION_LEVEL = 80;
VideoCapture cap(0); // Open the camera
if (!cap.isOpened()) { if (!cap.isOpened()) {
cerr << "Error: Could not open camera" << endl; cerr << "Error: Could not open camera" << endl;
return; return;
@@ -444,14 +446,21 @@ void CapnSend() {
} }
} }
// Convert the image to a byte array // Compress the image (JPEG compression with adjustable quality)
vector<uchar> buf; vector<uchar> buf;
imencode(".jpg", frame, buf); vector<int> compression_params;
auto *enc_msg = reinterpret_cast<unsigned char *>(buf.data()); compression_params.push_back(IMWRITE_JPEG_QUALITY); // Set JPEG quality
compression_params.push_back(COMPRESSION_LEVEL); // Adjust the quality level (0-100, lower = more compression)
// Publish the image data // Encode the image into the byte buffer with the specified compression parameters
client.publishMessage("kobuki/cam", string(enc_msg, enc_msg + buf.size())); imencode(".jpg", frame, buf, compression_params);
cout << "Sent image" << endl;
// Convert the vector<uchar> buffer to a string (no casting)
string enc_msg(buf.begin(), buf.end());
// Publish the compressed image data (MQTT, in this case)
client.publishMessage("kobuki/cam", enc_msg);
cout << "Sent compressed image" << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Send image every 200ms std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Send image every 200ms
} }