Skip to content

Instantly share code, notes, and snippets.

@panqiincs
Last active April 22, 2022 15:07
Show Gist options
  • Save panqiincs/fcc1ca952e6c8a6d9bef9cdcb0ea972d to your computer and use it in GitHub Desktop.
Save panqiincs/fcc1ca952e6c8a6d9bef9cdcb0ea972d to your computer and use it in GitHub Desktop.
Read image data from rpi camera, compress image data and send.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <raspicam/raspicam_cv.h>
#define oops(msg) { perror(msg); exit(1); }
int main(int argc, char **argv)
{
struct sockaddr_in saddr;
struct hostent *hp;
int portnum;
int listenfd, connfd;
if (argc < 3) {
fprintf(stderr, "Usage: %s hostname portnum\n", argv[0]);
exit(1);
}
hp = gethostbyname(argv[1]);
if (hp == NULL) {
fprintf(stderr, "No such host!\n");
exit(1);
}
portnum = atoi(argv[2]);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1) {
oops("socket");
}
bzero((void *)&saddr, sizeof(saddr));
bcopy((void *)hp->h_addr, (void *)&saddr.sin_addr, hp->h_length);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(portnum);
if (bind(listenfd, (struct sockaddr *)&saddr, sizeof(saddr)) != 0) {
oops("bind");
}
if (listen(listenfd, 1) != 0) {
oops("listen");
}
// 设置图像参数,打开摄像头
raspicam::RaspiCam_Cv camera;
camera.set(CV_CAP_PROP_FORMAT, CV_8UC3);
camera.set(CV_CAP_PROP_FRAME_WIDTH, 640);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
std::cout << "Openning camera...";
if (!camera.open()) {
std::cerr << "Error openning the camera!" << std::endl;
return -1;
}
std::cout << "Successfully!" << endl;
// 配置压缩参数
std::vector<int> param = std::vector<int>(2);
param[0] = CV_IMWRITE_JPEG_QUALITY;
param[1] = 95;
cv::Mat frame; // 存储一帧图像
std::vector<uchar> buff; // 存储压缩后的数据
char data_size_str[20]; // 字符串数组,压缩后数据的大小
for (;;) {
connfd = accept(listenfd, NULL, NULL);
printf("Receive a request!\n");
if (connfd == -1) {
oops("accept");
}
for (;;) {
camera.grab();
camera.retrieve(frame);
cv::imencode(".jpg", frame, buff, param); // 压缩图像
sprintf(data_size_str, "%d", buff.size()); // 将数据大小转换成字符
send(connfd, data_size_str, 15, 0); // 发送压缩数据的大小
send(connfd, &buff[0], buff.size(), 0); // 发送压缩数据
}
close(connfd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment