Python将图像转换为深褐色
这是一个课程项目问题。我正在处理这个函数“mono”,不确定我做错了什么。乌贼墨的配方如下: 要模拟深褐色的照片,请将绿色值变暗为int(0.6*亮度),将蓝色值变暗为int(0.4*亮度),生成红棕色色调 我在代码中使用了这个公式,我在课程检查模块中得到的错误是我的答案有76%的错误。有什么建议吗?下面是到目前为止我的代码Python将图像转换为深褐色,python,Python,这是一个课程项目问题。我正在处理这个函数“mono”,不确定我做错了什么。乌贼墨的配方如下: 要模拟深褐色的照片,请将绿色值变暗为int(0.6*亮度),将蓝色值变暗为int(0.4*亮度),生成红棕色色调 我在代码中使用了这个公式,我在课程检查模块中得到的错误是我的答案有76%的错误。有什么建议吗?下面是到目前为止我的代码 def mono(image, sepia=False): """ Returns True after converting
def mono(image, sepia=False):
"""
Returns True after converting the image to monochrome.
All plug-in functions must return True or False. This function returns True
because it modifies the image. It converts the image to either greyscale or
sepia tone, depending on the parameter sepia.
If sepia is False, then this function uses greyscale. For each pixel, it computes
the overall brightness, defined as
0.3 * red + 0.6 * green + 0.1 * blue.
It then sets all three color components of the pixel to that value. The alpha value
should remain untouched.
If sepia is True, it makes the same computations as before but sets green to
0.6 * brightness and blue to 0.4 * brightness.
Parameter image: The image buffer
Precondition: image is a 2d table of RGB objects
Parameter sepia: Whether to use sepia tone instead of greyscale
Precondition: sepia is a bool
"""
# We recommend enforcing the precondition for sepia
assert sepia == True or sepia == False
height = len(image)
width = len(image[0])
for row in range(height):
for col in range(width):
if sepia == False:
pixel = image[row][col]
pixel.red = int(0.3 * pixel.red + 0.6 * pixel.green + 0.1 * pixel.blue)
pixel.green = pixel.red
pixel.blue = pixel.red
for row in range(height):
for col in range(width):
if sepia == True:
pixel = image[row][col]
sepi = int(pixel.red + pixel.green * 0.6 + pixel.blue * 0.4)
# Change this to return True when the function is implemented
return True
如注释中所述,您不使用
sepi
值。此外,还可以组合这两个循环
def mono(image, sepia=False):
height = len(image)
width = len(image[0])
for row in range(height):
for col in range(width):
pixel = image[row][col]
# Do the b&w calculation on the red pixel
# Don't convert to int yet so we can use it later
new_value = 0.3 * pixel.red + 0.6 * pixel.green + 0.1 * pixel.blue
pixel.red = int(new_value)
if sepia:
# Do extra calculations on green & blue if sepia
pixel.green = int(new_value * 0.6)
pixel.blue = int(new_value * 0.4)
else:
pixel.green = pixel.red
pixel.blue = pixel.red
return True
您从未将
sepi
的值分配给任何对象-您可能希望将其分配回像素(就像你在灰度版本中所做的那样?同样,问题开始时的断言实际上没有任何作用,因为它测试sepia是真是假——它将是其中之一。与其在图像上迭代两次,在循环中测试sepia,不如在它上面迭代一次,然后确定设置为r/g/b的值根据sepia
是真是假。非常感谢。我确实需要合并这些循环。现在我知道我在计算的方式上做错了什么。非常感谢您的帮助。