问题描述
我应该编写一种方法,使用“平均方法”将RGB图像转换为灰度图像,其中取3种颜色的平均值(非加权方法或亮度方法) 。然后,我必须将原始的RGB图像和灰度图像彼此相邻显示(串联)。我正在使用的语言是Python。这是我的代码当前的样子。
import numpy as np
import cv2
def getRed(redVal):
return '#%02x%02x%02x' % (redVal,0)
def getGreen(greenVal):
return '#%02x%02x%02x' % (0,greenVal,0)
def getBlue(blueVal):
return '#%02x%02x%02x' % (0,blueVal)
# Grayscale = (R + G + B / 3)
# For each pixel,# 1- Get pixels red,green,and blue
# 2- Calculate the average value
# 3- Set each of red,and blue values to average value
def average_method(img):
for p in img:
red = p.getRed()
green = p.getGreen()
blue = p.getBlue()
average = (red + green + blue) / 3
p.setRed(average)
p.setGreen(average)
p.setBlue(average)
def main():
img1 = cv2.imread('html/images/sun.jpeg')
img1 = cv2.resize(img1,(0,0),None,.50,.50)
img2 = average_method(img1)
img2 = np.stack(3 * [img2],axis=2)
numpy_concat = np.concatenate((img1,img2),1)
cv2.imshow('Numpy Concat',numpy_concat)
cv2.waitKey(0)
cv2.destroyAllWindows
if __name__ =="__main__":
main()
average_method函数中要注释的部分是我必须遵循的步骤。
当我尝试运行代码时,我得到
File "test.py",line 38,in <module>
main()
File "test.py",line 30,in main
img2 = average_method(img1)
File "test.py",line 15,in average_method
red = p.getRed()
AttributeError: 'numpy.ndarray' object has no attribute 'getRed'
我认为在上面定义getRed,getGreen和getBlue的函数将意味着它们将在我的average_method函数中变得可识别(我从网上获得了这些函数,所以我希望它们是正确的)。我也不确定与numpy.ndarray有什么关系。如果有人可以帮助我用正确遵循注释步骤的代码填写此average_method函数,我将不胜感激。
编辑::: 新代码如下:
import cv2
import numpy as np
def average_method(img):
for p in img:
gray = sum(p)/3
for i in range(3):
p[i] = gray
def main():
img1 = cv2.imread('html/images/sun.jpeg')
img1 = cv2.resize(img1,numpy_concat)
cv2.waitKey(0)
cv2.destroyAllWindows
if __name__ =="__main__":
main()
我现在得到了错误
File "test.py",line 50,line 43,in main
img2 = np.stack(3 * [img2],axis=2)
File "<__array_function__ internals>",line 5,in stack
File "C:\Users\myname\AppData\Local\Programs\Python\python38-32\lib\site-packages\numpy\core\shape_base.py",line 430,in stack
axis = normalize_axis_index(axis,result_ndim)
numpy.AxisError: axis 2 is out of bounds for array of dimension 1
我有那行“ img2 = np.stack(3 * [img2],axis = 2)”,因为我之前在堆栈溢出中被告知,由于我的img2现在是灰度(单通道)图像,所以我需要它,当img1仍然是彩色(三通道)时。这行显然可以解决该问题。但是现在看来这有问题吗?
解决方法
在Java中,您突出显示的for循环称为“增强的for循环”。 Python没有这些功能,因为Python for loops循环(简明扼要)。
该行的Python等效项为:
for p in img:
无需声明对象类或类似内容。
编辑:OP更改问题后
现在的问题是您没有正确调用函数。 p是一个包含该像素的RGB值的数组。要调用上面定义的函数,请执行以下操作:
for p in img:
red = getRed(p[0])
green = getGreen(p[1])
blue = getBlue(p[2])
average = (red + green + blue) / 3
p[0] = average
p[1] = average
p[2] = average
请记住,当您将代码移至Python时,您似乎不再在面向对象编程中工作!像素不再带有您可以像这样调用的方法。
但是,正如Guimoute在评论中所指出的,如果您摆脱了get [Color]函数并执行以下操作,则代码可能会更加简单:
for p in img:
gray = sum(p)/3
for i in range(3):
p[i] = gray