Converting pixels colour creates noise

Viewed 81

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

1 Answers

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

Related