OpenCV返回黑白图像,而不是灰度图像 [英] OpenCV returns black and white image instead of grayscale

查看:319
本文介绍了OpenCV返回黑白图像,而不是灰度图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  1. 戴上口罩
  2. 收获结果
  3. 最后,将像素值缩放为255

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

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

以下是当我尝试按255撤消缩放比例时获得的输出(第3步)

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

以下是预期的输出

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

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

推荐答案

这是因为数据类...我认为crop矩阵类是uchar,当您除以255时,输出为0或1 (介于0到254之间的每个强度为零,而255为1),当您在255中乘以输出时,输出将为0和255. 所以测试这段代码

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

这篇关于OpenCV返回黑白图像,而不是灰度图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆