Jad Fouk Aladeh
Jad Fouk Aladeh

Reputation: 1

Image manipulation, using openCV and numpy. Trying to return an image without the color red

I am trying to take in a image, checking pixel by pixel if there is any red in it.

If there is it'll replace it with white. Once it runs through every pixel, it'll return a new image with white instead of red.

The following are my attempts:

import cv2
import numpy as np

def take_out_red():
'''
Takes an image, and returns the same image with red replaced
by white
------------------------------------------------------------
Postconditions:
returns
new_img (no red) 
'''
img = cv2.imread('red.png',1)
#Reads the image#

new_img = img
#Makes a copy of the image
for i in range(499):
    for y in range(499):
        if np.all(img[i,y]) == np.all([0,0,253]):
            #[0,0,253] is a red pixel 
            #Supposed to check if the particular pixel is red
            new_img[i,y] == [255,255,255]
            #if it is red, it'll replace that pixel in the new_image
            #with a white pixel
return cv2.imshow('image',new_img)
#returns the new_image with no red 

Any help would be highly appreciated, thank you so much in advance.

Upvotes: 0

Views: 411

Answers (2)

ZdaR
ZdaR

Reputation: 22954

When you have OpenCV or numpy at your service, then you probably don't need to write double iterating for loops which are not clean and inefficient as well. Both the libraries have very efficient routines to iterate a n-D array and apply basic operations such as checking equality etc.

You can use cv2.inRane() method to segment the red color from the input image and then use powerful numpy to replace the color using the mask obtained from the cv2.inRange() as:

import cv2
import numpy as np

img = cv2.imread("./sample_img.png")

red_range_lower = np.array([0, 0, 240])
red_range_upper = np.array([0, 0, 255])
replacement_color = np.array([255, 0, 0])
red_mask = cv2.inRange(img, red_range_lower, red_range_upper)
img[red_mask == 255] = replacement_color

cv2.imwrite("./output.png", img)

Input:

enter image description here

Output:

enter image description here

Upvotes: 1

Asher Mancinelli
Asher Mancinelli

Reputation: 304

If img[i,y] == [0,0,255]:

is your issue. You’re trying to compare something with two values to something with three, and there’s no way to check that.

Upvotes: 0

Related Questions