OpenCV returns 黑白图像代替灰度图

OpenCV returns black and white image instead of grayscale

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

  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)时得到的输出

以下是预期输出

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

这是因为 class 的数据......我假设 crop 矩阵 class 是 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;
}