gpt4 book ai didi

haskell - 如何将图像转换为颜色矩阵?

转载 作者:行者123 更新时间:2023-12-04 02:47:34 25 4
gpt4 key购买 nike

我正在玩 Graphics.GD,我想将图像读入 Color 值的矩阵,有点像这样:

rectFromImage :: Image -> IO [[Color]]
rectFromImage img = do
size <- imageSize img
return [[getPixel (x,y) img | x <- [1 .. fst size]] | y <- [1 .. snd size]]

显然,这不起作用,因为 getPixel 返回 IO Color,而不是 Color:

Couldn't match type `IO Color' with `Foreign.C.Types.CInt'
Expected type: Color
Actual type: IO Color
In the return type of a call of `getPixel'
In the expression: getPixel (x, y) img
In the expression: [getPixel (x, y) img | x <- [1 .. fst size]]

如何在 getPixel 调用的返回中“摆脱 IO”?

最佳答案

sequence 是您正在寻找的神奇功能。 sequence 接受一个 IO 操作列表,并使它成为一个 IO 值列表。在类型签名方面:

sequence :: Monad m => [m a] -> m [a]

或者,更具体地说,您的情况:

sequence :: [IO a] -> IO [a]

所以你可以这样做,例如:

do
putStrLn "Enter three lines of input:"
irritatedUser <- sequence [getLine, getLine, getLine]
putStrLn (irritatedUser !! 2)

并且用户写的最后一行将被打印回来。

无论如何,在你的情况下,这意味着你想要做

rectFromImage img = do
size <- imageSize img
sequence [sequence [getPixel (x,y) img | x <- [1 .. fst size]] | y <- [1 .. snd size]]

我在其中偷偷调用了两个 sequence 调用,从您的 [[IO Color]][IO [Color]]然后是 IO [[Color]]

一般来说,你永远不会“摆脱”IO,你只是向上传播它。

关于haskell - 如何将图像转换为颜色矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com