使用opencv在灰度图像中绘制彩色矩形 [英] Drawing a colored rectangle in a grayscale image using opencv

查看:652
本文介绍了使用opencv在灰度图像中绘制彩色矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用opencv在灰度图像中绘制彩色矩形. 我尝试了几种方法,但是整个图像都变成了灰度或RGB.

Is it possible to draw a colored rectangle in a grayscale image using opencv. I tried several ways but either the whole image turns grayscale or RGB.

推荐答案

您不能混合使用灰色和彩色图像.您可以查看是否可以在同一图像opencv C ++中同时具有灰度和RGB像素?.

You can't have a mixed gray and color image. You can have a look at Is there a way to have both grayscale and rgb pixels on the same image opencv C++?.

因此,您不能在灰度CV_8UC1图像上绘制彩色矩形.但是您可以将其绘制在显示灰色图像的CV_8UC3图像上.

So you can't draw a colored rectangle on a grayscale CV_8UC1 image. But you can draw it on a CV_8UC3 image that shows your gray image.

您可以使用cvtColor(..., ..., COLOR_GRAY2BGR)创建CV_8UC3 灰色图像,然后在其上绘制彩色矩形,例如:

You can create a CV_8UC3 gray-colored image with cvtColor(..., ..., COLOR_GRAY2BGR), and then you can draw your colored rectangle on it, e.g:

请注意,此图像不再是CV_8UC1类型,而是CV_8UC3类型.

Note that this image, however, is no more of type CV_8UC1, but CV_8UC3 instead.

#include <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    Mat1b gray = imread("path_to_image", IMREAD_GRAYSCALE);

    // Convert gray image to BGR
    Mat3b grayBGR;
    cvtColor(gray, grayBGR, COLOR_GRAY2BGR);

    // Draw the colored rectangle
    rectangle(grayBGR, Rect(10, 10, 100, 200), Scalar(0,255,0), 2);

    imshow("Image with Rect", grayBGR);
    waitKey();

    return 0;
}

这篇关于使用opencv在灰度图像中绘制彩色矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆