2

just a quick question: I am loading a black and white image and then replacing the black and/or white pixels with other colors. The problem is when I visualize the edited image there are some black pixels, like noise, around the white segments.

Input image: Input image

Here is how I iterate through the pixels:

img1_black[np.where((img1_black == [0, 0, 0]).all(axis=2))] = [0, 255, 0]
cv2.imshow("Result4", img1_black)

second method of iterating:

img1_black_pixels_mask = np.all(mask_1 == [0, 0, 0], axis=-1)
img1_non_black_pixels_mask = np.any(mask_1 != [0, 0, 0], axis=-1)
img1_black[img1_black_pixels_mask] = [0, 0, 255]
img1_black[img1_non_black_pixels_mask] = [0, 255, 0]
plt.imshow(img1_black)
plt.show()

First Output image Output image

Second Output image Second Output image 2

2
  • 2
    You are working on a grayscale image (values in range [0-255]) but mask out only completely black pixels (range [0]). The pixels aroung the white blobs are almost completely black pixels (range [1-20]). Try fist to threshold the image and then apply the rest of your code. See this
    – Shir
    Commented Mar 5, 2021 at 12:22
  • Yes, that was the thing. Thanks for the answer! Commented Mar 5, 2021 at 12:30

1 Answer 1

1

This will help you.

import cv2
import numpy as np

image = cv2.imread("pmjpl.jpg")

gray_scale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, threshold_image = cv2.threshold(gray_scale, 100, 255, cv2.THRESH_BINARY)
cv2.imshow("threshold_image", threshold_image)

colour_image = cv2.cvtColor(threshold_image, cv2.COLOR_GRAY2BGR)

mask = colour_image[:, :, 0] == 255  # mask for white pixels
colour_image[mask] = [0, 0, 255]  # fill red colour for white pixels

mask = colour_image[:, :, 2] == 0  # mask for black pixels
colour_image[mask] = [0, 255, 0]  # fill green colour for white pixels

cv2.imshow("colour_image", colour_image)

cv2.waitKey(0)
cv2.destroyAllWindows()

threshold_image clolur_image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.