B.rabbit
B.rabbit

Reputation: 69

Unable to imwrite to PNG even though imshow works

Does anyone know why even though I could imshow the image stored in grad, I am unable to write it using imwrite? I searched the web and it seems like it might be a floating point issue, but I do not know of any way to make the floating points in the matrix of an image disappear.

int main( int argc, char** argv ) {

    cv::Mat src, src_gray;
    cv::Mat grad;
    char* window_name = "Sobel Demo - Simple Edge Detector";
    int scale = 1;
    int delta = 0;
    int ddepth = CV_16S;

    int c;

    /// Load an image
    src = imread("C:/Users/Qi Han/Dropbox/44.jpg" );

    if( !src.data ) return -1;

    GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT );

    /// Convert it to gray
    cvtColor( src, src_gray, CV_RGB2GRAY );

    /// Create window
    namedWindow( window_name, CV_WINDOW_AUTOSIZE );

    /// Generate grad_x and grad_y
    Mat grad_x, grad_y;
    Mat abs_grad_x, abs_grad_y;

    /// Gradient X 
    //Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT );
    Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );
    convertScaleAbs( grad_x, abs_grad_x );

    /// Gradient Y    
    //Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
    Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );
    convertScaleAbs( grad_y, abs_grad_y );

    /// Total Gradient (approximate)
    addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );
    imshow( window_name, grad );
    imwrite("C:/Users/Qi Han/Dropbox/aftsobel.png", grad);
    return 0;
}

Upvotes: 0

Views: 1975

Answers (2)

herohuyongtao
herohuyongtao

Reputation: 50667

Try to imwrite a BMP image instead or use Mat::convertTo and cvtColor to convert it before saving.

From imwrite documentation:

[...] Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo() , and cvtColor() to convert it before saving. [...]

Upvotes: 3

Eran W
Eran W

Reputation: 1776

read the docs of imwrite:

Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo() , and cvtColor() to convert it before saving.

Upvotes: 0

Related Questions