0

Currently, I am facing troubles with coloring the pink boxes with adjacent colors, so that the image would look more real. My image is this:

enter image description here

So far, I used CV2 package and achieved this:

enter image description here

My code:

up = np.array([151,157,255])
pink_mask = cv2.inRange(img, up, up)
cnts, _ = cv2.findContours(pink_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
    color = tuple(map(int, img[0, 0]))
    cv2.fillPoly(img, pts=[c], color=color)

Here, I filled with the first pixel on the image, as I am not sure how to fill it with the adjacent colors.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • This doesn't fill the mask with the nearest pixel but perhaps this is what you want [cv2.inpaint](https://docs.opencv.org/3.4/df/d3d/tutorial_py_inpainting.html) – Steven97102 May 18 '23 at 08:49

2 Answers2

1

We may dilate the mask, and use cv2.inPaint:

import numpy as np
import cv2

img = cv2.imread('input.png')

up = np.array([151,157,255])
pink_mask = cv2.inRange(img, up, up)
#cnts, _ = cv2.findContours(pink_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# for c in cnts:
#     color = tuple(map(int, img[0, 0]))
#     cv2.fillPoly(img, pts=[c], color=color)
pink_mask = cv2.dilate(pink_mask, np.ones((3, 3), np.uint8))  # Dilate the mask

img = cv2.inpaint(img, pink_mask, 5, cv2.INPAINT_TELEA)

cv2.imwrite('output.png', img)

Output:
enter image description here

Rotem
  • 30,366
  • 4
  • 32
  • 65
0

Use 'cv2.boundingRect[c]' to get the current contours' x, y, w and h. If you want to fill in the colour based on the left hand side of the detected contour, use (x - 5, y). And if you want to fill in the colour based on the right side, use (x + w + 5, y).

Note that 5 is just an offset used. You can start at 1.