OpenCV returns black and white image instead of grayscale

倖福魔咒の 提交于 2019-12-12 04:57:58

问题


The following is my attempt to preprocess an image. That involves the followings steps

  1. Apply a mask
  2. Crop the result
  3. Finally, scale the pixel values by 255

When I try to go back from step 3 to step 2, I get a black and white image instead of a grayscale one. The following is my code to perform preprocessing

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;
}

The following is the output that I get when I try to undo scaling by 255(step 3)

The following is the expected output

What causes the image to be black and white instead of grayscale?


回答1:


It's because class of data... I assume that the crop matrix class is uchar and when you divide to 255 the output is 0 or 1 (every intensity between 0 to 254 is zero and 255 will be 1) and when you multipy output in 255 the output will be 0 and 255. so test this code

{
.
.
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;
}


来源:https://stackoverflow.com/questions/45393464/opencv-returns-black-and-white-image-instead-of-grayscale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!