gpt4 book ai didi

c++ - openCV 更改颜色后不会复制到图像(opencv 和 c++)

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:55 24 4
gpt4 key购买 nike

我是opencv的初学者。我有这个任务:

  1. 制作新图片

  2. 在0,0处放一张特定的图片

  3. 将某张图片转为灰度

  4. 将灰度图像放在它旁边(在 300, 0 处)

我就是这样做的。我有一个类 imagehandler,它具有构造函数和所有函数。

cv::Mat m_image

是成员字段。

制作新图像的构造函数:

imagehandler::imagehandler(int width, int height)
: m_image(width, height, CV_8UC3){


}

构造函数从文件中读取图像:

imagehandler::imagehandler(const std::string& fileName)
: m_image(imread(fileName, CV_LOAD_IMAGE_COLOR))
{
if(!m_image.data)
{
cout << "Failed loading " << fileName << endl;
}

}

这是转换为灰度的函数:

void imagehandler::rgb_to_greyscale(){

cv::cvtColor(m_image, m_image, CV_RGB2GRAY);

}

这是复制粘贴图片的函数:

//paste image to dst image at xloc,yloc
void imagehandler::copy_paste_image(imagehandler& dst, int xLoc, int yLoc){

cv::Rect roi(xLoc, yLoc, m_image.size().width, m_image.size().height);
cv::Mat imageROI (dst.m_image, roi);

m_image.copyTo(imageROI);
}

现在,大体上,这就是我所做的:

imagehandler CSImg(600, 320); //declare the new image
imagehandler myimg(filepath);

myimg.copy_paste_image(CSImg, 0, 0);
CSImg.displayImage(); //this one showed the full colour image correctly
myimg.rgb_to_greyscale();
myimg.displayImage(); //this shows the colour image in GRAY scale, works correctly
myimg.copy_paste_image(CSImg, 300, 0);
CSImg.displayImage(); // this one shows only the full colour image at 0,0 and does NOT show the greyscaled one at ALL!

问题是什么?我已经为这个问题绞尽脑汁好几个小时了!!!

最佳答案

您遇到以下问题:

在构造函数而不是

m_image(width, height, CV_8UC3){}

你应该写

{  
m_image.create(width, height, CV_8UC3);
}

相反,不用担心默认构造。

备注:

  • 我不确定 cvtColor 在与输入和输出相同的 Mat 下是否正常工作,我认为将其更改为 Mat temp 更安全; cvtColor(m_image, temp, CV_...); m_image=temp;
  • 您可以通过调用 m_image.empty() 而不是检查 !m_image.data 来检查图像是否为空。否则你无法确定。由于重新计算的资源管理,指针 m_image.data 也可能过时。
  • 在你之前的问题中,我看到了一个自定义析构函数:你不需要那个,不用担心。

关于c++ - openCV 更改颜色后不会复制到图像(opencv 和 c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13478941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com