# Cannot change pixel value of image

**URL:** <https://forum.opencv.org/t/cannot-change-pixel-value-of-image/2809>\
**Category:** C++\
**Tags:** mat, core\
**Created:** [April 17, 2021, 7:36am UTC](https://forum.opencv.org/t/cannot-change-pixel-value-of-image/2809 "2021-04-17T07:36:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gvert](https://avatars.discourse-cdn.com/v4/letter/g/a6a055/32.png) [@gvert](https://forum.opencv.org/u/gvert)\
**Post date:** [April 17, 2021, 7:36am UTC](https://forum.opencv.org/t/cannot-change-pixel-value-of-image/2809/1 "2021-04-17T07:36:39Z")

</div>

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

  }
```

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [April 17, 2021, 7:51am UTC](https://forum.opencv.org/t/cannot-change-pixel-value-of-image/2809/2 "2021-04-17T07:51:15Z")

</div>

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](https://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#a33fd5d125b4c302b0c9aa86980791a77), like in:

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

---

<div class="post-metadata">

**Author:** ![gvert](https://avatars.discourse-cdn.com/v4/letter/g/a6a055/32.png) [@gvert](https://forum.opencv.org/u/gvert)\
**Post date:** [April 17, 2021, 7:56am UTC](https://forum.opencv.org/t/cannot-change-pixel-value-of-image/2809/3 "2021-04-17T07:56:00Z")

</div>

Ah that’s right, thank you!
