Ask Your Question
0

Error in changing the background color from white to black

asked 2018-03-13 02:28:00 -0600

AhmedSh3ban gravatar image

hello. i am trying to change the background color to black. it's white so i am trying to go throught all the pixels and check whether its white or no if so change the value to 0. but somthing went wrong here is my code.

Mat img = imread("t.PNG");
for (int x = 0; x < img.rows; x++)
{
    for (int y = 0; y < img.cols; y++)
    {
        if (img.at<Vec3b>(Point(x, y))[0] >=245 && img.at<Vec3b>(Point(x, y))[1] >= 245 && img.at<Vec3b>(Point(x, y))[2] >= 245)
        {

            img.at<Vec3b>(Point(x, y)) = { 0,0,0 };
        }       
    }   
}
imwrite("img.png",img);
imshow(" ",img);
waitKey(0);

 here is the image i am trying to convert

edit retag flag offensive close merge delete

Comments

  • you seem to be lost about x,y, rows and cols. go over that again, and DON'T swap the semantics of it !
  • don't write per-pixel loops, ever.
  • what's the problem ? you forgot to mention !
berak gravatar imageberak ( 2018-03-13 03:04:27 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2018-03-13 03:17:27 -0600

berak gravatar image

updated 2018-03-13 03:19:03 -0600

please STOP writing per-pixel loops. you're shooting your own foot above with confusing x and y in multiple ways, and in general, the opencv way would be to use some existing higher level functions instead, like:

Mat im = imread("brain.png");

// make a mask, where everything white in the image is set to black
Mat mask; 
compare(im, Scalar::all(245), mask, CMP_GT);

// delete all pixels, where the mask is "off"
im.setTo(Scalar::all(0), mask);

imshow("B",im);

image description

edit flag offensive delete link more

Comments

Thanks. it works fine. the error i was getting was in the if Codintion. it says "OpenCV Error: Assertion failed (((((sizeof(size_t)<<28)|0x8442211) >> ((traits::Depth<_Tp>::value) & ((1 << 3) - 1))*4) & 15) == elemSize1()) in cv::Mat::at, file c:\opencv\build\include\opencv2\core\mat.inl.hpp, line 1118"

AhmedSh3ban gravatar imageAhmedSh3ban ( 2018-03-14 02:12:20 -0600 )edit

^^ yes, buffer overflow due to broken indexing.

berak gravatar imageberak ( 2018-03-14 02:21:38 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-03-13 02:28:00 -0600

Seen: 1,392 times

Last updated: Mar 13 '18