摄像头识别颜色值

#include "stdio.h"
#include "math.h"
#include "string.h"
#include "stdlib.h"

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <pthread.h>
// #include "/usr/local/opencv2/include/opencv2/contrib/contrib.hpp"
#include "opencv2/imgproc/types_c.h"
#include <opencv2/opencv.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "app_uart.h"
#include <opencv2/stitching.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/video.hpp>
#include <opencv2/core/core_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <iostream>
#include <string>
#include <unistd.h>

using namespace cv;
using namespace std;

const char *keys =
	{
		"{help h usage ? | | print this message}"
		"{@video | | Video file, if not defined try to use webcamera}"
		"{face_cascade|/home/lwp/opencv/opencv/data/haarcascades/haarcascade_frontalface_alt.xml|Path to face cascade.}"
		"{helmet_cascade|/mnt/hgfs/ubutu/SVM_HOG.xml|Path to helmet cascade.}"};

int get_frame_rgb(Mat frame)
{
	int r, g, b;
	// 获取图像的中心区域 (假设图像尺寸较大,选择中心区域的大小为 100x100)
	int centerX = frame.cols / 2;
	int centerY = frame.rows / 2;

	int width = 100;  // 中心区域的宽度
	int height = 100; // 中心区域的高度
	// printf("\r\n");
	//  提取中心区域
	Rect roi(centerX - width / 2, centerY - height / 2, width + 70, height);
	Mat centerRegion = frame(roi);

	// imshow("centerRegion", centerRegion);

	// 计算该区域的平均颜色值
	Scalar meanColor = mean(centerRegion);
	r = meanColor[2];
	g = meanColor[1];
	b = meanColor[0];
	// 输出中心区域的平均颜色值 (BGR)
	// printf("AAACenter Region Average Color: B=%f, G=%f, R=%f\n", meanColor[0], meanColor[1], meanColor[2]);

	Mat colorCircle1 = Mat::zeros(200, 200, CV_8UC3);
	circle(colorCircle1, Point(100, 100), 80, Scalar(b, g, r), -1);
	// imshow("Color", colorCircle1);
	///////////////////////////////////////////////////////////////////////////////////

	// 转换图像为 HSV
	cv::Mat rgb(1, 1, CV_8UC3, cv::Scalar(b, g, r));
	cv::Mat hsv;
	cv::cvtColor(rgb, hsv, cv::COLOR_BGR2HSV);	   // 需要用BGR到HSV的转换
	cv::Vec3b hsv_value = hsv.at<cv::Vec3b>(0, 0); // 获取转换后的HSV值
	// printf("Center Region Average Color: H=%f, S=%f, V=%f\n", (float)hsv_value[0], (float)hsv_value[1], (float)hsv_value[2]);

	// 饱和度系数修改
	float avgH = (float)hsv_value[0];
	float avgS = (float)((float)hsv_value[1] * (float)1.3);
	float avgV = (float)((float)hsv_value[2] * (float)0.9);

	if (avgH > 179)
		avgH = 179;
	if (avgS > 255)
		avgS = 255;
	if (avgV > 255)
		avgV = 255;

	Mat hsvPixel(1, 1, CV_8UC3);
	hsvPixel.at<Vec3b>(0, 0) = Vec3b(avgH, avgS, avgV);
	Mat bgrPixel;
	cvtColor(hsvPixel, bgrPixel, COLOR_HSV2BGR);
	Vec3b bgrValue = bgrPixel.at<Vec3b>(0, 0);

	b = bgrValue[0];
	g = bgrValue[1];
	r = bgrValue[2];

	app_uart_send(r, g, b, 0);
	// printf("BBBCenter Region Average Color: B=%d, G=%d, R=%d\n", b, g, r);

	Mat colorCircle = Mat::zeros(200, 200, CV_8UC3);
	circle(colorCircle, Point(100, 100), 80, Scalar(b, g, r), -1);
	// imshow("Color Circle", colorCircle);
}

// video
int main(int argc, char *argv[])
{
	int mnu = 0;
	int i = 0;
	static int count = 0;
	for (i = 0; i < argc; i++)
		printf("%s ", argv[i]);
	printf("\r\n");

	uart_task_init(NULL);
	CommandLineParser parser(argc, argv, keys);

	parser.about("Reading a video and camera v1.0.0");

	if (parser.has("help"))
	{
		parser.printMessage();
		return -1;
	}
	String videoFile = parser.get<String>(0);
	// std::cout << videoFile << std::endl;
	if (!parser.check())
	{
		parser.printErrors();
		return -1;
	}
	VideoCapture cap;
	if (videoFile != "")
	{
		cap.open(videoFile); // read a video file
	}
	else
	{
		cap.open(0); // read the default caera  //方式2
	}
	// cap.open("/dev/video0");//方式2
	if (!cap.isOpened()) // check if we succeeded
	{
		return -1;
	}

	while (1)
	{
		Mat frame, yuvImg;
		cap >> frame; // get a new frame from camera

		if (frame.empty())
		{
			break;
		}

		// imshow("Capture", frame);
		// detectAndDisplay(frame);
		// printf("opencv-frame %d \r\n", count++);
		if (waitKey(1) == 27)
		{
			break;
		}
		mnu++;
		if (mnu >= 5)
		{
			get_frame_rgb(frame);
			mnu = 0;
		}
		usleep(1000);
	}

	return 0;
}

串口

#include "app_uart.h"
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <memory.h>
#include <termio.h>
#include <errno.h>
#include <iostream>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
bool mIsOpen = false;

int mUartID = 0;
/**
 * @brief
 * @param baudRate
 */
int app_uart_init(speed_t baudRate)
{
    mUartID = open(LME_UART_FILE_NAME, O_RDWR | O_NOCTTY | O_NDELAY);

    struct termios options;
    if (mUartID < 0)
    {
        mIsOpen = false;
        printf("uart_open fail, err.\n");
        return -1;
    }

    // 获取串口配置
    if (tcgetattr(mUartID, &options) < 0)
    {
        perror("Unable to get port settings\r\n");
        return -1;
    }

    // 设置波特率
    cfsetispeed(&options, baudRate); // 输入波特率
    cfsetospeed(&options, baudRate); // 输出波特率

    // 设置数据位、停止位和奇偶校验
    options.c_cflag &= ~PARENB; // 无奇偶校验
    options.c_cflag &= ~CSTOPB; // 1位停止位
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;            // 8数据位
    options.c_cflag |= CREAD | CLOCAL; // 启用接收和忽略调制解调器控制线

    // 使设置生效
    if (tcsetattr(mUartID, TCSANOW, &options) < 0)
    {
        perror("Unable to set port settings\r\n");
        return -1;
    }

    mIsOpen = true;
    // printf("lme_uart_open success, ok.\n");
    return 1;
}
/**
 * @brief
 * @param pData
 * @param len
 * @return
 */
int writeData(uint8_t *pData, int len)
{
    if (write(mUartID, pData, len) != (int)len)
    {
        // fail
        // printf("uart_send Fail\n");
        return -1;
    }
    return 0;
}

int readData(char *buffer, int size)
{
    int bytes_read = read(mUartID, buffer, size);
    if (bytes_read <= 0)
    {
        // perror("Failed to read from serial port\r\n");
        return 0;
    }
    buffer[bytes_read] = '\0'; // Null-terminate the string
    return bytes_read;
}
/**
 * @brief 发送数据
 * @param R
 * @param G
 * @param B
 * @param W
 */
void app_uart_send(int R, int G, int B, int W)
{
    uint8_t RGBW[5] = {0};
    RGBW[0] = 0xA5;
    RGBW[1] = abs(R);
    RGBW[2] = abs(G);
    RGBW[3] = abs(B);
    RGBW[4] = abs(W);
    // printf("Color: B=%d, G=%d, R=%d\n", abs(RGBW[1]), abs(RGBW[2]), abs(RGBW[3]));
    if (mIsOpen == true)
        writeData(&RGBW[0], 5);
}
void *task_function(void *arg)
{
    char rbuf[100] = {0};
    int rlen = 0;
    while (1)
    {
        rlen = readData(&rbuf[0], 100);
        if (rlen > 0)
        {
            // printf("rbuf:%s\r\n", &rbuf[0]);
        }
        // printf("This is the new thread. Thread ID = %lu\n", pthread_self());
        usleep(1);
    }
    return NULL;
}
void uart_task_init(void *arg)
{
    pthread_t thread_id; // 线程 ID
    app_uart_init(B9600);
    // 创建一个新线程
    int result = pthread_create(&thread_id, NULL, task_function, NULL);
    if (result != 0)
    {
        // 错误处理
        // perror("Thread creation failed\r\n");
    }
    // 等待新线程结束
    // pthread_join(thread_id, NULL);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌风_lwp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值