2012-11-20 40 views
1

我是opencv的初學者。 我有這樣的任務:openCV在更改顏色後不會複製到圖像(opencv和C++)

  1. 創建一個新的形象

  2. 把某種形象在它在0,0

  3. 轉換的特定圖像灰度

  4. 放在它旁邊的灰度圖像(在300,0)

這就是我所做的。 我有一個類圖像處理程序,它具有構造函數和所有函數。

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! 

出了什麼問題?我一直在這個問題上搔着頭!

回答

2

您有以下問題:

在構造函數,而不是

m_image(width, height, CV_8UC3){} 

你應該寫

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

來代替,而不用擔心默認的建設。

備註:

  • 林不知道cvtColor正常工作具有相同墊作爲輸入和輸出,我認爲它是安全將其更改爲Mat temp; cvtColor(m_image, temp, CV_...); m_image=temp;
  • 您可以檢查圖像爲空,通過調用m_image.empty()不通過檢查!m_image.data。否則你不能確定。由於refcounted資源管理,指針m_image.data也可能陳舊。
  • 從你早先的問題,我看到了一個自定義的析構函數:你不需要那個,不用擔心。
+0

工作,謝謝。 – TheNotMe