Ask Your Question
2

Unable to detect black pixels ?

asked 2015-03-16 05:46:35 -0600

begueradj gravatar image

updated 2015-03-16 05:50:32 -0600

I am reading a picture to color in red all its black pixels (the background only is black):

import numpy as np
import cv2

second=cv2.imread('second.png')

for i in range(second.shape[0]):
   for j in range(second.shape[1]):
       if second[i,j,0]!=0 and second[i,j,1]!=0 and second[i,j,2]!=0:
           second[i,j,0]=0
           second[i,j,1]=0
           second[i,j,2]=255
cv2.imwrite('result.png',second)

Here is the image second.png:

enter image description here

Here is the colored image result.png: enter image description here

Why not all the yellow rose is not colored in red ? Note when I print those pixels that are not colored (in red in result.png) in second.png I see they are not black. Why this ?

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
4

answered 2015-03-16 05:51:35 -0600

updated 2015-03-16 07:03:07 -0600

Have you heard of cv::inrange or cv::threshold? Yellow is 255,255,0 in RGB, so I guess your yellow pixels in the final image have a B-value of zero and are therefore not turned to red. Maybe you want to write (now without typos):

if not (second[i,j,0]==0 and second[i,j,1]==0 and second[i,j,2]==0):
  turn_pixel_red();
edit flag offensive delete link more

Comments

3

Thank you very much , (however, you have 2 typos, = must be == and ! must be not)

begueradj gravatar imagebegueradj ( 2015-03-16 05:59:45 -0600 )edit
1

answered 2016-03-26 19:21:48 -0600

a test code around the question

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    char* filename = argc >= 2 ? argv[1] : (char*)"61nj0.png";
    Mat src = imread( filename );

    if(src.empty())
    {
        return -1;
    }

    imshow("source",src);

    Mat gray,dst;
    cvtColor(src,gray,COLOR_BGR2GRAY);
    cvtColor(gray,dst,COLOR_GRAY2BGR);

    dst = dst - Scalar(127,127,0);
    imshow("result 1",dst);

    Mat bgr[3];
    split(src,bgr);

    Mat mZero = Mat::zeros(src.size(),CV_8UC1);
    Mat bgr1[3]= {mZero,mZero,bgr[1]};
    merge(bgr1,3,dst);
    imshow("result 2",dst);

    Mat bgr2[3]= {bgr[0],mZero,bgr[1]};
    merge(bgr2,3,dst);
    imshow("result 3",dst);
    waitKey();
}

image description

image description

image description

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2015-03-16 05:46:35 -0600

Seen: 2,285 times

Last updated: Mar 26 '16