Python将图像转换为深褐色

2024-05-26 11:12:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个课程项目问题。我正在处理这个函数“mono”,不确定我做错了什么。乌贼墨的配方如下: 要模拟深褐色的照片,请将绿色值变暗为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

Tags: thetoinimagefalsetrueforis
1条回答
网友
1楼 · 发布于 2024-05-26 11:12:53

如注释中所述,您不使用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

相关问题 更多 >