Detection of certain pixels of a grayscale image

ぃ、小莉子 提交于 2020-12-13 07:08:18

问题


I have this code that allows you to detect pixels of a vertain value. Right now I'm detecting pixels over a certain value (27). My idea would be to still detect them but to detect another pixel values (I want to detec pixels from 65 to 75, another interval of pixels). How can I do this?

As you may see, T'm detecting grayscale images, so I have this same value for red, green and blue.

Any idea to improve this program in order to work faster would be really appreciated. Sucha as using os.walk to introduce all images from the Daytime folder that I don't reaaly know how to do it.

Thanks.

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

回答1:


A few ideas:

  • if, as you say, your images are greyscale, then you should process them as single-channel greyscale images, rather than needlessly tripling their memory footprint and tripling the number of comparisons you need to make by promoting them to RGB

  • rather than use nested for loops which are miserably slow in Python, either use Numpy or OpenCV to gain 10x to 1000x speedup. Similar example here.

  • if you have many images to process, they are all independent, and you have a decent CPU and RAM, consider using multiprocessing to get all your lovely cores processing images in parallel. Simple example here.


The second suggestion is most likely to yield the best dividend, so I'll expand that:

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)

That yields 2,200 for this 400x100 image:



来源:https://stackoverflow.com/questions/64513858/detection-of-certain-pixels-of-a-grayscale-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!