簡體   English   中英

我如何制作一個 function 迭代圖像中的所有像素以使用 numpy 找到指定的顏色

[英]How do i make a function that iterate over all the pixels in an image to find a specified colour using numpy

我正在嘗試制作一個 function,它使用雙循環遍歷圖像 (png) 中的所有像素以查找所有紅色像素。 function 應返回 numpy 中的二維數組,表示 output 二進制圖像,並將二維數組寫入新的 jpg 文件。 我只能使用 numpy、matplotlib 和 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))

這是我到目前為止所擁有的,但我被困住了。 如果 r > upper_threshold,g < lower_threshold 且 b < lower_threshold,則像素為紅色

您的代碼的唯一問題是語法:

  • '.data/map.png'替換為map_filename ,這是您 function 的輸入。
  • 刪除map_filename=mat_plot.imread('./data/map.png')之間的空行。
  • map_filename.astype(np.uint8)替換為rgb.astype(np.uint8)

話雖如此...

使用 NumPy 的要點是你可以用矩陣運算代替循環,這使得代碼更快,更容易閱讀。 這是使用 NumPy 和 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM