Cannot change pixel value of image

I have the average RGB value of a region of an image (‘child’ in this case) and after I find the best image that has the closest RGB value to the one in child , I want to create another image by replacing the pixels in the child image with the pixels in the matching image( and do this for each child/region of the original image). I tried this below. All the other methods work fine and I get an image where the first row of image regions is the desired output but then is just noise. If I change the img2.atcv::Vec3b(i,j)[0] to a constant value for example, it works. Anyone has any idea why this doesn’t work?

  for(Node child: kids)
  {
      RGBvalues val= child.average(img,child.getX(),child.gety(),child.getW(),child.getH());
      cv::Mat final;
      final = comparerColorQuad(val,images,tree); // final image that matches best
      cv::resize(final,final,cv::Size(child.getW(),child.getH()));


      for(int i = child.gety(); i < child.gety() + child.getH(); i++)
        for(int j = child.getX(); j < child.getX() + child.getW(); j++)
        {    cv::Vec3b pixelRGB=final.at<cv::Vec3b>(i,j);
            img2.at<cv::Vec3b>(i,j)[0]=pixelRGB[0];
            img2.at<cv::Vec3b>(i,j)[1]=pixelRGB[1];
            img2.at<cv::Vec3b>(i,j)[2]=pixelRGB[2];
        }

  }

please do NOT write loops like that, they’re slow, error prone, and defeat the purpose of a high-level matrix library like opencv

you already got x,y wrong, it’s at(row,col) in opencv

please rather copy a whole ROI, like in:

Rect child_rect(child.getX(),child.gety(),child.getW(),child.getH()));
final.copyTo(img2(child_rect));
1 Like

Ah that’s right, thank you!