python-3.x 我如何找到这亮度的像素在一个图像上使用一条线轮廓

jaxagkaj  于 2023-11-20  发布在  Python
关注(0)|答案(2)|浏览(126)

我试图找到沿着一条水平线穿过图像的像素的亮度,但我被困在如何得到一个数字数组,或者使用一个循环来改变x值并输出像素的值,这样我就可以计算每个像素的亮度,然后我可以在那条线上求平均值。这是我到目前为止得到的:

from PIL import Image
from math import sqrt
import os 
image = Image.open(os.path.join("mypath", "a.jpg"))
import numpy as np
image = imag.convert ('RGB')
X,Y = (137, 137) #this is where i dont know what else to add
pixelRGB = imag.getpixel((X,Y))
R,G,B = pixelRGB
brightness =([R,G,B])/3
print(brightness)

字符串
我不知道如何添加一个循环。

7rfyedvj

7rfyedvj1#

你应该用一个循环从0到width

from PIL import Image

image = Image.open("1.png")
width, height = image.size
y = 137

brightness_values = []

# Loop through the horizontal line
for x in range(width):
    pixelRGB = image.getpixel((x, y))
    R, G, B = pixelRGB
    brightness = (R + G + B) / 3  
    brightness_values.append(brightness)

print(brightness_values)

average_brightness = sum(brightness_values) / len(brightness_values)
print(f"Average brightness: {average_brightness}")

字符串

41zrol4v

41zrol4v2#

在Python中使用for循环处理图像速度慢且容易出错。请尝试使用Pillow的内置函数或向量化的Numpy函数。
首先,使用枕头:

from PIL import Image, ImageStat

# Create 256x256 image whose rows will have different means depending on the y-value
im = Image.radial_gradient('L').convert('RGB')

字符串


的数据

# Crop out row 64
row64 = im.crop((0,64,im.width,65))

# Get statistics for that row
stats = ImageStat.Stat(row64)

# Print means
print(stats.mean)

输出:

[133.3984375, 133.3984375, 133.3984375]


其次,使用Numpy:

from PIL import Image
import numpy as np

# Create 256x256 image whose rows will have different means depending on the y-value
im = Image.radial_gradient('L').convert('RGB')


# Convert to Numpy array
na = np.array(im)

# print mean of row 0, row 64 and row 128
print(np.mean(na[0]), np.mean(na[64]), np.mean(na[128]))


打印值:

207.3203125 133.3984375 90.01171875


如果您希望计算沿沿着 * 任何 * 线(不一定是垂直或水平线)的平均值(或线轮廓),则可以使用scikit-image

from PIL import Image
import numpy as np
from skimage.draw import line

# Create 256x256 image whose rows will have different means depending on the y-value
im = Image.radial_gradient('L').convert('RGB')


# Convert to Numpy array
na = np.array(im)

# Get row/column coordinates of diagonal line from top-left to bottom-right
rr, cc = line(0,0, 255,255)

# Get means of points along diagonal
result = np.mean(na[rr,cc])

相关问题