在 python 中将过滤器变暗为图像8.7.10 变暗过滤器代码

问题描述

我正在尝试编写一个 darken_filter 和一个 change_picture 函数,将图像左半部分的像素修改为更暗。非常感谢帮助。这是我当前的代码

# Constants for the image
IMAGE_URL = "https://codehs.com/uploads/e07cd01271cac589cc9ef1bf012c6a0c"
IMAGE_WIDTH = 280
IMAGE_HEIGHT = 200
DARKENING_FACTOR = 50
MIN_PIXEL_VALUE = 0

image = Image(IMAGE_URL)
image.set_position(70,70)
image.set_size(IMAGE_WIDTH,IMAGE_HEIGHT)
add(image)

# This function should take a pixel and return a tuple
# with the new color
def darken_filter(pixel):
    pass

# This function should loop through each pixel on the
# left hand side and call the darken filter to calculate 
# the new color then update the color.
def change_picture():
    pass            

# Give the image time to load
print("Making Darker....")
print("Might take a minute....")
timer.set_timeout(change_picture,1000)

解决方法

使用 PILLOW 将图像一分为二

使用 ImageEnhance 模块中的 class PIL.ImageEnhance.Brightness(image),该模块包含许多可用于图像增强的类

类 PIL.ImageEnhance.Brightness(image):

'调整图像亮度。

该类可用于控制图像的亮度。 0.0 的增强因子给出黑色图像。系数 1.0 给出原始图像。'

重新构图

无法真正解决半尺寸图像也许最好将您的问题分成两个问题,但我尝试使用 PIL.ImageEnhance.Brightness(image),Image.point() 对下面的假定图像代码进行变暗过滤器部分正如在网上找到的和对你的方法的尝试,我确信在第三种方法中有一种更直接的方法,但我也是一个新手,可能遗漏了一些东西:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb  6 16:38:32 2021

@author: Pietro

"""

from PIL import Image,ImageEnhance

import numpy as np

image_input = Image.open('Immagine_6.tif')

image_input.show()

print(image_input.size)
print(image_input.mode)

image_input = image_input.convert('RGB')

# method one from https://www.daniweb.com/programming/software-development/code/216419/darken-lighten-an-image-python
# Image.point() : https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=image.point#PIL.Image.Image.point
image_output =image_input.point(lambda p: p * 0.5)

image_output.show()


# method two using ImageEnhance module of pillow
# https://pillow.readthedocs.io/en/3.0.x/reference/ImageEnhance.html#PIL.ImageEnhance.Brightness
enhancer = ImageEnhance.Brightness(image_input)

image_output_2 = enhancer.enhance(0.1)

image_output_2.show()

# method three your method sure there is a better way than this one 
# This function should take a pixel and return a tuple
# with the new color
def darken_filter(pixel):
            pixel = (0.3*np.array(pixel)).astype('int')
            pixel = tuple(pixel[0:3])
            return pixel

image_input_dark = image_input.copy()

for x in range(image_input_dark.size[0]):
    for y in range(image_input_dark.size[1]):
        i = image_input_dark.getpixel((x,y))
        ii = darken_filter(i)
        image_input_dark.putpixel((x,y),ii)
    
image_input_dark.show()

示例图片

sample image