Rgb图像转灰度图像

问题描述 投票:0回答:1

我有一张 RGB 格式的激光束图像。我想通过将图像转换为灰度来获取图像的亮度。

但事实证明这不是我的计划。中心应该是最亮的地方,结果却很暗 求助,谁知道

enter image description here

enter image description here

from PIL import Image
import math

image = Image.open("/content/TiSa_fs_vert_1.jpg")
image = image.convert ('RGB')
width, height = image.size
y = 450

brightness_values = []

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

print(brightness_values)
python image rgb grayscale
1个回答
0
投票

你很幸运,因为你使用的是激光,它将是单色的并且很容易从颜色通道中分离出来

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2

img = np.array(Image.open("laser.jpg"))

plt.figure()
plt.imshow(img)
plt.show()
# Since the laser is red, you can just take out the red channel from the RGB
# Color channels are 0=Red, 1=Green, 2=Blue
r=img[:,:,0]
plt.figure()
plt.imshow(r, cmap='grey') 
plt.show()

# To plot only the brightest portion of your selected channel, you can do:
threshold= r.max()*0.9
# set areas of the image that are below the threshold to be 0
r[np.where(r<threshold)]=0
# set areas of the image that are at or above the threshold to be 1
r[np.where(r>=threshold)]=1

plt.figure()
plt.imshow(r, cmap='grey')
plt.show()

# To clean up the image a bit more
cleaned_up = cv2.dilate(r,np.ones((3,3), dtype=np.uint8),iterations = 5)
plt.figure()
plt.imshow(cleaned_up, cmap='grey')
plt.show()

# Simplistic method to calculate center
# (you should probably apply some smoothing to the calculated brightness along each axis)
x_sum = cleaned_up.sum(axis=0)
y_sum = cleaned_up.sum(axis=1)
center = (x_sum.max(), y_sum.max())
plt.figure()
plt.plot(np.arange(x_sum.shape[0]),x_sum)
plt.plot(y_sum,np.arange(y_sum.shape[0]))
plt.show()

plt.figure()
plt.imshow(cleaned_up, cmap='grey')
plt.plot(center[0],center[1], 'ro')
plt.show()

# Using image moments to find the centroid
moments = cv2.moments(cleaned_up)
centroid = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
plt.figure()
plt.imshow(cleaned_up, cmap='grey')
plt.plot(centroid[0],centroid[1], 'ro')
plt.show()

说实话,这两种寻找中心的方法都工作得很好,并且产生非常相似的结果,但我更喜欢使用图像矩的质心方法,因为它在我眼中看起来更集中,但请随意选择最适合的方法你

© www.soinside.com 2019 - 2024. All rights reserved.