[英]Detection of certain pixels of a grayscale image
我有这段代码可以让你检测一个 vertain 值的像素。 现在我正在检测超过某个值 (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
一些想法:
如果,正如你所说,你的图像是灰度的,那么你应该将它们作为单通道灰度图像处理,而不是不必要地将它们的 memory 足迹增加三倍,并通过将它们提升为 RGB 来将你需要进行的比较次数增加三倍
与其使用在 Python 中速度非常慢的嵌套for
循环,不如使用Numpy或OpenCV来获得 10 到 1000 倍的加速。 类似的例子在这里。
如果你有很多图像要处理,它们都是独立的,并且你有一个不错的 CPU 和 RAM,考虑使用多处理来让你所有可爱的内核并行处理图像。 简单的例子在这里。
第二个建议最有可能产生最好的红利,所以我将扩展它:
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:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.