I am trying to make a function that uses a double for loop to traverse all pixels in an image (png) to find all the red pixels. The function should return a 2D array in numpy representing the output binary image and writes the 2D array into a new jpg file. I can only use numpy, matplotlib and skimage.
import numpy as np
from matplotlib import pyplot as mat_plot
def find_red_pixels(map_filename, upper_threshold=100, lower_threshold=50):
"""
Returns a 2D array in numpy representing the output binary image and writes the 2D array into a file
"""
map_filename =
mat_plot.imread('./data/map.png')
map_filename = map_filename * 255 # Scale the color values from [0 – 1] range to [0 – 255] range
rgb = np.array(map_filename)
row, col = rgb.shape
for i in range(0, row):
for j in range(0, col):
color = rgb[i,j]
if(color[0] > upper_threshold):
if(color[1] < lower_threshold):
if(color[2] < lower_threshold):
rgb[i,j] = [0,0,0]
mat_plot.imsave('map-red-pixels.jpg', map_filename.astype(np.uint8))
This is what i have so far but i am stuck. A pixel is red if r > upper_threshold, g < lower_threshold and b < lower_threshold
The only problem with your code is the syntax:
'.data/map.png'
by map_filename
, which is the input of your function.map_filename=
and mat_plot.imread('./data/map.png')
.map_filename.astype(np.uint8)
by rgb.astype(np.uint8)
.The point of using NumPy is that you can replace loops by matrix operations, which makes the code faster and easier to read. This is an alternative solution for your problem using NumPy and Matplotlib.
def find_red_pixels(_image: str, up_threshold: float, low_threshold: float) -> None:
image = plt.imread(_image) * 255
rgb = image * np.array([[[-1.0, 1.0, 1.0]]])
threshold = np.array([[[-up_threshold, low_threshold, low_threshold]]])
new_image = image - image * np.all(rgb - threshold < 0.0, axis=2)[:, :, None]
plt.imsave("no_red_image.jpg", new_image.astype(np.uint8))
return None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.