opencv改变像素点的颜色---------c++

改变像素点的颜色

cpp 复制代码
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <filesystem>

bool opencvTool::changeColor(const std::string image_p, int x_coor, int y_coor, const cv::Scalar color)
{
	std::filesystem::path file(image_p);
	if (!std::filesystem::exists(file))
	{
		std::cout << image_p << " is not exist" << std::endl;
		return false;
	}
	cv::Mat ima = cv::imread(image_p.c_str()); // 读取图像,替换为你的图片路径  
	cv::Scalar Red = cv::Scalar(0, 0, 255);  // Red color  

	if (x_coor> ima.cols || x_coor < 0)
	{
		printf("Input x_coor: %d which exceeds width range of the image: %d \n", x_coor, ima.cols);
		return false;
	}
	if (y_coor > ima.rows || y_coor< 0)
	{
		printf("Input y_coor: %d which exceeds height range of the image: %d \n", y_coor, ima.rows);
		return false;
	}

	// 改变像素点的颜色
	ima.at<cv::Vec3b>(y_coor, x_coor)[0] = 0;
	ima.at<cv::Vec3b>(y_coor, x_coor)[1] = 0;
	ima.at<cv::Vec3b>(y_coor, x_coor)[2] = 255;

	// 或者
	//uchar blue = 0;
	//uchar green = 0;
	//uchar red = 255;
	//ima.at<cv::Vec3b>(y_coor, x_coor) = cv::Vec3b(blue, green, red);

	cv::imwrite(image_p.c_str(), ima);
	return true;

}

bool opencvTool::changeColor(cv::Mat& image, int x_coor, int y_coor, const cv::Scalar color)
{
	if (image.empty())
	{
		std::cout << "Error: empty mat" << std::endl;
		return false;
	}

	if (x_coor > image.cols || x_coor < 0)
	{
		printf("Input x_coor: %d which exceeds width range of the image: %d \n", x_coor, image.cols);
		return false;
	}
	if (y_coor > image.rows || y_coor < 0)
	{
		printf("Input y_coor: %d which exceeds height range of the image: %d \n", y_coor, image.rows);
		return false;
	}

	// 更改指定坐标点的颜色
	image.at<cv::Vec3b>(y_coor, x_coor) = cv::Vec3b(color[0], color[1], color[2]);

	return true;
}
相关推荐
草莓熊Lotso14 分钟前
C++ 继承特殊场景解析:友元、静态成员与菱形继承的底层逻辑
服务器·开发语言·c++·人工智能·经验分享·笔记·1024程序员节
利刃大大33 分钟前
【动态规划:01背包】01背包详解 && 模板题 && 优化
c++·算法·动态规划·力扣·背包问题
9ilk42 分钟前
【基于one-loop-per-thread的高并发服务器】--- 前置技术
运维·服务器·c++·笔记·后端·中间件
苏比的博客3 小时前
Windows MFC添加类,变量,类导向
c++·windows·mfc
yudiandian20143 小时前
MFC - 使用 Base64 对图片进行加密解密
c++·mfc
yudiandian20143 小时前
MFC - Picture Control 控件显示图片
c++·mfc
我是李武涯8 小时前
从`std::mutex`到`std::lock_guard`与`std::unique_lock`的演进之路
开发语言·c++
卡提西亚8 小时前
C++笔记-10-循环语句
c++·笔记·算法
亮剑20189 小时前
第1节:C语言初体验——环境、结构与基本数据类型
c++
William_wL_9 小时前
【C++】类和对象(下)
c++