【问题标题】:Detection of certain pixels of a grayscale image检测灰度图像的某些像素
【发布时间】:2021-02-07 08:04:44
【问题描述】:

我有这段代码可以让你检测一个特定值的像素。现在我正在检测超过某个值(27)的像素。我的想法是仍然检测它们,但检测另一个像素值(我想检测从 65 到 75 的像素,另一个像素间隔)。我该怎么做?

如您所见,T'正在检测灰度图像,因此我对红色、绿色和蓝色具有相同的值。

任何改进此程序以加快工作速度的想法将不胜感激。比如使用 os.walk 来介绍 Daytime 文件夹中我不知道怎么做的所有图片。

谢谢。

daytime_images = os.listdir("D:/TR/Daytime/")
number_of_day_images = len(daytime_images)
day_value = 27

def find_RGB_day(clouds, red, green, blue): 
    img = Image.open(clouds) 
    img = img.convert('RGB') 
    pixels_single_photo = [] 
    for x in range(img.size[0]): 
        for y in range(img.size[1]): 
            h, s, v, = img.getpixel((x, y)) 
            if h <= red and s <= green and v <= blue:
                pixels_single_photo.append((x,y)) 
    return pixels_single_photo

number = 0

for _ in range(number_of_day_images):
    world_image = ("D:/TR/Daytime/" + daytime_images[number])
    pixels_found = find_RGB_day(world_image, day_value, day_value, day_value)
    coordinates.append(pixels_found)
    number = number+1

【问题讨论】:

    标签: python image pixel grayscale os.walk


    【解决方案1】:

    一些想法:

    • 如您所说,如果您的图像是灰度图像,那么您应该将它们作为单通道灰度图像进行处理,而不是通过将它们提升为 RGB 来不必要地将它们的内存占用增加三倍并增加三倍的比较次数

    • 与其使用嵌套的 for 循环,后者在 Python 中非常慢,而是使用 NumpyOpenCV 来获得 10 倍到 1000 倍的加速。类似的例子here

    • 如果您有许多图像要处理,它们都是独立的,并且您有一个不错的 CPU 和 RAM,请考虑使用多处理来让所有可爱的内核并行处理图像。简单例子here


    第二个建议最有可能产生最好的红利,所以我将扩展它:

    from PIL import Image
    import Numpy as np
    
    # Open an image and ensure greyscale
    im = Image.open('image.png').convert('L')
    
    # Make into Numpy array
    na = np.array(im)
    
    # Make a new array that is True where pixels between 65..75 and False elsewhere
    x = np.logical_and(na>65,na<75)
    
    # Now count the True pixels
    result = np.count_nonzero(x)
    

    对于这张 400x100 的图像,这会产生 2,200:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 2023-02-20
      • 1970-01-01
      • 2012-06-01
      • 2017-11-17
      相关资源
      最近更新 更多