如何从(大多数)图片中提取 RGB 值?

How to extract RGB values from (most) pictures?

我想从 Haskell 中可能的图片中提取每个 RGB 值。

获取原始值 (0-255) 的最简单方法是什么?

我已经使用 Juicy Pixels 库获得了一些结果,但不知何故我总是得到异常:

*** Exception: ./Data/Vector/Generic.hs:249 ((!)): index out of bounds (660000,660000)

这是对应的代码。

{-# LANGUAGE TypeSynonymInstances #-}

module Main where

import Codec.Picture         (readImage, pixelAt, PixelRGB8(..))
import Codec.Picture.Types
import System.FilePath.Posix (splitExtension)

toRGBRaw :: FilePath -> IO ()
toRGBRaw fp = do
    image <- readImage fp
    case image of
      Left _ -> putStrLn $ "Sorry, not a supported codec for " ++ fp
      Right dynimg -> do
        let imgrgba8 = fromDynamicImage dynimg
        let (name, _) = splitExtension fp
        writeFile (name ++ ".txt") (concat $ accumPixels imgrgba8)

accumPixels :: Image PixelRGBA8 -> [String]
accumPixels img@(Image w h _) = [ format (pixelAt img x y) x y | x <- [0..w], y <- [0..h]]
  where format (PixelRGBA8 r g b _) j k = "#" ++ show r ++ "$"
                                              ++ show g ++ "$"
                                              ++ show b ++ "$"
                                              ++ show j ++ "$"
                                              ++ show k ++ "*\n"


-- Copied from
-- See http://hackage.haskell.org/package/JuicyPixels-util-0.2/docs/Codec-Picture-RGBA8.html

class ToPixelRGBA8 a where
    toRGBA8 :: a -> PixelRGBA8

instance ToPixelRGBA8 Pixel8 where
    toRGBA8 b = PixelRGBA8 b b b 255

instance ToPixelRGBA8 PixelYA8 where
    toRGBA8 (PixelYA8 l a) = PixelRGBA8 l l l a

instance ToPixelRGBA8 PixelRGB8 where
    toRGBA8 (PixelRGB8 r g b) = PixelRGBA8 r g b 255

instance ToPixelRGBA8 PixelRGBA8 where
    toRGBA8 = id

fromDynamicImage :: DynamicImage -> Image PixelRGBA8
fromDynamicImage (ImageY8 img) = pixelMap toRGBA8 img
fromDynamicImage (ImageYA8 img) = pixelMap toRGBA8 img
fromDynamicImage (ImageRGB8 img) = pixelMap toRGBA8 img
fromDynamicImage (ImageRGBA8 img) = img

-- end of Codec.Picture.RGBA8

这是示例图片:Link

代码目前有点乱序,因为我不得不从 Codec.Picture.RGBA8 复制一些定义,而 LTS 无法提供这些定义。不要介意字符串表示,我正在通过带有 WiFi 屏蔽的 Arduino 解析它们。

您在 accumPixels 中的列表理解是 0 索引的,但也包括边界。这可能是问题所在。在 Haskell 中,[0..3] 是列表 [0,1,2,3],因此您可能指的是 [0..(w-1)][0..(h-1)]