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;
}
相关推荐
迷迭所归处5 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林5 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice6 小时前
2024.9.19
c++
天玑y6 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸2336 小时前
c++ static(详解)
开发语言·c++
菜菜想进步6 小时前
内存管理(C++版)
c语言·开发语言·c++
Joker100857 小时前
C++初阶学习——探索STL奥秘——模拟实现list类
c++
科研小白_d.s7 小时前
vscode配置c/c++环境
c语言·c++·vscode
湫兮之风7 小时前
c++:tinyxml2如何存储二叉树
开发语言·数据结构·c++
友友马8 小时前
『 Linux 』HTTP(一)
linux·运维·服务器·网络·c++·tcp/ip·http