【问题标题】:OpenCV returns black and white image instead of grayscaleOpenCV 返回黑白图像而不是灰度图像
【发布时间】:2018-01-05 16:51:14
【问题描述】:

以下是我对图像进行预处理的尝试。这涉及以下步骤

  1. 应用蒙版
  2. 裁剪结果
  3. 最后,将像素值缩放 255

当我尝试从第 3 步返回到第 2 步时,我得到的是黑白图像而不是灰度图像。 以下是我执行预处理的代码

cv::Mat maskCrop(std::string imageName, std::string maskName)
{
    cv::Mat image,mask;
    image = cv::imread( imageName, CV_LOAD_IMAGE_GRAYSCALE);
    mask = cv::imread( maskName,CV_LOAD_IMAGE_GRAYSCALE);
    cv::Mat final_image;
    cv::resize(image, image, mask.size());  // make the size of mask and image same
    
    cv::bitwise_and(image, mask, final_image); //Apply mask
    
    // define rectangular window for cropping
    int offset_x = 1250;  // top left corner, for cropping
    int offset_y = 1550;
    
    cv::Rect roi;
    roi.x = offset_x;
    roi.y = offset_y;
    roi.width = 550;
    roi.height = 650;
    
    // Crop the original image to the defined ROI //
    
    cv::Mat crop = final_image(roi);
   //scale the image
    float beta = 1.0 / 255.0;
    crop *=beta;  // divide the max pixel vaue i.e. 255
    
    //Examinig whether scaling can be undone !!!!
    cv::imwrite("/home/dpk/Desktop/ip-rings/gray_image.jpg",crop*255);
    
    return crop;
}

以下是我尝试撤消缩放 255(步骤 3)时得到的输出

以下是预期的输出

是什么导致图像是黑白而不是灰度?

【问题讨论】:

  • crop 矩阵的数据类型是无符号 8 位整数。将其乘以浮点标量不会改变这一点。

标签: c++ opencv grayscale


【解决方案1】:

这是因为数据类...我假设crop 矩阵类是uchar,当您除以 255 时,输出为 0 或 1(0 到 254 之间的每个强度都为零,255 将为 1 ) 并且当您将输出乘以 255 时,输出将为 0 和 255。 所以测试这段代码

{
.
.
cv::Mat crop = final_image(roi);
crop.convertTo(crop,
               CV_32F,       //New Type
               1.0f/255,     //Scaling
               0);           //offset
cv::imwrite("/home/dpk/Desktop/ip-rings/gray_image.jpg",crop*255);

return crop;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多