欢迎访问宙启技术站
智能推送

用Python和Haskell实现的图像处理应用案例

发布时间:2023-12-09 10:55:22

使用Python和Haskell可以实现各种图像处理应用。下面是两个案例,分别介绍了如何用Python和Haskell实现图像的模糊效果和黑白效果。

Python案例:模糊效果

from PIL import Image, ImageFilter

def blur_image(input_image_path, output_image_path):
    image = Image.open(input_image_path)
    blurred_image = image.filter(ImageFilter.BLUR)
    blurred_image.save(output_image_path)

# 示例用法
input_path = "input.jpg"
output_path = "blurred_output.jpg"
blur_image(input_path, output_path)

上述代码中,首先使用PIL库中的Image类打开输入图片,然后使用ImageFilter.BLUR创建一个模糊滤镜,将其应用于输入图片并保存到输出路径中。这样,就得到了一个模糊效果的图像。

Haskell案例:黑白效果

import Codec.Picture

toGreyscale :: DynamicImage -> Image Pixel8
toGreyscale (ImageRGB8 img) = pixelMap rgbToGrey img
toGreyscale (ImageRGBA8 img) = pixelMap rgbaToGrey img
toGreyscale (ImageYCbCr8 img) = pixelMap yCbCrToGrey img
toGreyscale _ = error "Unsupported image format"

rgbToGrey :: PixelRGB8 -> Pixel8
rgbToGrey (PixelRGB8 r g b) = floor (0.21 * (fromIntegral r) + 0.72 * (fromIntegral g) + 0.07 * (fromIntegral b))

rgbaToGrey :: PixelRGBA8 -> Pixel8
rgbaToGrey (PixelRGBA8 r g b _) = rgbToGrey (PixelRGB8 r g b)

yCbCrToGrey :: PixelYCbCr8 -> Pixel8
yCbCrToGrey (PixelYCbCr8 y _ _) = y

main :: IO ()
main = do
    inputImage <- readImage "input.jpg"
    case inputImage of
        Left err -> putStrLn $ "Error loading image: " ++ err
        Right dynamicImage -> do
            let greyscaleImage = toGreyscale dynamicImage
            savePngImage "greyscale_output.png" $ ImageY8 greyscaleImage

上述代码中,首先使用Codec.Picture库中的readImage函数加载输入图片,然后使用toGreyscale函数将输入图片转化为灰度图像。最后,使用savePngImage函数保存灰度图像到输出路径中,得到一个黑白效果的图像。

这两个案例展示了使用Python和Haskell实现图像处理应用的基本思路和方法。你可以修改和扩展这些代码来实现更复杂的图像处理应用,如调整对比度、改变色彩等。