这是一个课程项目问题。我正在研究这个“单声道”功能,但不确定我做错了什么。棕褐色的公式如下: 要模拟棕褐色调的照片,您将绿色值变暗为 int(0.6 * 亮度),将蓝色值变暗为 int(0.4 * 亮度),从而产生红褐色调。
我在我的代码中使用了这个公式,我在课程检查模块中得到的错误是我的答案有 76% 不正确。对我有什么建议吗?以下是我目前的代码。
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
答案 0 :(得分:1)
如评论中所述,您不使用 sepi
值。此外,您可以组合 2 个循环。
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