How do you sum up and average a Sequence?

泄露秘密 提交于 2019-12-13 04:41:30

问题


Say I have a coordinate (x, y) and its neighbors in a sequences of sequence (-1, 1)(0, 1)(1, 1)(-1, 0)(0, 0)(1, 0)(-1, -1)(0, -1)(1, -1)

let n = [1 .. -1 .. -1]
|> Seq.collect (fun j -> [-1 .. 1] |> Seq.map(fun i -> [i, j]))
n |> Seq.iter(printf "%A")
  1. I'm trying to add x and y to each element in the sequence respectively
  2. Then get Color p = GetPixel(x+i, y+j) for every element in sequence, sum up and average out their R, G, B for (x,y)
  3. So we have 9 Red, 9 Green, 9 Blue to Ave(Red), Ave(Blue), Ave(Green)

回答1:


let offsets = seq { for i in -1 .. 1 do for j in -1 .. 1 do yield (i, j) }
let neighbourhood (x, y) = Seq.map (fun (i, j) -> (x + i, y + j)) offsets
let avgColours (cs : System.Drawing.Color seq) =
        let ((r, g, b), c) = cs |> Seq.fold (fun ((r, g, b), c) col -> ((r + int col.R, g + int col.G, b + int col.B), c + 1)) ((0, 0, 0), 0)
        System.Drawing.Color.FromArgb(r / c, g / c, b / c)

let avgNeighbours p = p |> neighbourhood |> Seq.map (fun (x, y) -> GetPixel(x, y)) |> avgColours



回答2:


Something like this?

let f x y = 
    let n = [1 .. -1 .. -1] |> Seq.collect (fun j -> [-1 .. 1] |> Seq.map(fun i -> (i, j)))
    n |> Seq.map (fun (i,j) -> x+i,y+j)
      |> Seq.map bitmapobject.GetPixel
      |> Seq.map (fun c -> float c.R, float c.G, float c.B)
      |> Seq.fold (fun (R,G,B) (r,g,b) -> (R+r, G+g, B+b)) (0.0, 0.0, 0.0)
      |> (fun (r,g,b) -> (r/9.0, g/9.0, b/9.0)) 


来源:https://stackoverflow.com/questions/22824274/how-do-you-sum-up-and-average-a-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!