[C++] opencv中如何生成随机颜色?

27 篇文章 1 订阅

我们可以通过C++来生成OpenCV绘图使用的随机颜色,代码如下:

#include <iostream>
#include <opencv2/opencv.hpp>
#include <ctime>

int main()
{
    // 获取当前时间点
    auto now = std::chrono::system_clock::now();
    
    // 将时间点转换为time_t类型
    std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
    
    // 初始化随机数种子
    srand(static_cast<unsigned int>(currentTime)); 
    // 或者
    // srand(static_cast<unsigned int>(time(0)));

    // 生成随机颜色
    //cv::Vec3b randomColor(rand() % 256, rand() % 256, rand() % 256);
    cv::Scalar randomColor(rand() % 256, rand() % 256, rand() % 256);

    // 创建一个随机颜色的图像
    cv::Mat image(100, 100, CV_8UC3, randomColor);

    // 显示图像
    cv::imshow("Random Color Image", image);
    cv::waitKey(0);

    return 0;
}

这个代码将生成一个大小为100x100像素的随机颜色图像。它首先使用当前时间作为随机数种子来初始化随机数生成器。然后,它使用rand()函数生成三个介于0到255之间的随机整数,分别表示红色、绿色和蓝色通道的值。最后,它使用这些值创建一个cv::Vec3b类型或cv::Scalar的向量,并将其用作图像的像素值。

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++OpenCV,可以使用连通组件标记函数connectedComponentsWithStats()来获取图像的连通组件信息,并使用不同的颜色绘制出每个连通组件。 下面是一个示例代码,演示了如何使用连通组件标记函数和绘制函数来实现连通组件绘色: ```cpp #include <opencv2/opencv.hpp> using namespace cv; int main() { // 读取图像 Mat image = imread("input.jpg", IMREAD_GRAYSCALE); // 进行连通组件标记 Mat labels, stats, centroids; int num_labels = connectedComponentsWithStats(image, labels, stats, centroids); // 创建一个彩色图像,用于绘制连通组件 Mat colored_image; cvtColor(image, colored_image, COLOR_GRAY2BGR); // 随机生成颜色 RNG rng(0); vector<Vec3b> colors(num_labels); for (int i = 0; i < num_labels; i++) { colors[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256)); } // 绘制连通组件 for (int y = 0; y < image.rows; y++) { for (int x = 0; x < image.cols; x++) { int label = labels.at<int>(y, x); if (label > 0) { colored_image.at<Vec3b>(y, x) = colors[label]; } } } // 显示结果图像 imshow("Connected Components", colored_image); waitKey(0); return 0; } ``` 这段代码首先读取了一张灰度图像,然后使用connectedComponentsWithStats()函数进行连通组件标记,得到每个连通组件的标签。接下来,创建一个彩色图像,用于绘制连通组件。然后,随机生成颜色,并根据每个像素的标签将对应的颜色绘制到彩色图像上。最后,显示结果图像。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

老狼IT工作室

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

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

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

打赏作者

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

抵扣说明:

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

余额充值