Question

I'm trying to convert an imported colored picture to greyscale.

Here is what i tried so far, but mathematica simple crashes after executing this code, maybe you can find the error, can't recognize what I'm doing wrong:

SetDirectory[NotebookDirectory[]]
testimage = Import["test.jpg"]
matrixpic = getMatrix[testimage]

matrixpic = getMatrix[testimage]
greypic = 
  Graphics[
    Raster[
        matrixpic, {{0, 0}, {sizeX[matrixpic], sizeY[matrixpic]}}, {0, 
        255}, ColorFunction -> (GrayLevel[#[[1]]*0.3 + #[[2]]*0.5 + #[[
        3]]*0.2] &)
    ], 
    ImageSize -> {sizeX[matrixpic], sizeY[matrixpic]}, 
    AspectRation -> Automatic
 ]

 Show[greypic]
Was it helpful?

Solution 2

This works and is more Mathematica style code.

SetDirectory[NotebookDirectory[]];
img = Import["55th-All-Japan-Kendo-Champ2007-4.jpg"];
colorXform[p_] := p[[1]]*0.3 + p[[2]]*0.5 + p[[3]]*0.2;
newImg = Image[Map[colorXform, ImageData[img], {2}]];
Show[newImg]

OTHER TIPS

I believe the best way to make this conversion is to use ImageApply and Dot:

img = Import["ExampleData/lena.tif"]

enter image description here

ImageApply[{.3, .5, .2}.# &, img]

enter image description here


Please ask your future questions on the dedicated Mathematica StackExchange site:

enter image description here

Your code can be simplified to

img = Import["ExampleData/lena.tif"];
matrixpic = ImageData[img, DataReversed -> True];
Graphics[Raster[matrixpic, 
  ColorFunction -> (GrayLevel[{.3, .5, .2}.#] &)]]

This works without errors in Mathematica 8.0.4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top