Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Image:get() Returns the Wrong Value

in Questions Posts: 103

Hey guys!
In my latest project I need to copy the colors of pixels of an image into rectangles in a mesh, but using image:get() seems to return the wrong value. I noticed that the new value changes depending on the alpha value, so I tried multiplying the red, green, and blue values by 255/alpha and it looks like it fixed the problem (switch lines 13 and 14) but I'm not sure if it's the best way to do it.
Thanks!

function setup()
    img1 = image(50,50)
    fill(0,35,255,127)
    setContext(img1)
    ellipse(25,25,50)
    setContext()
    img2 = image(50,50)
    for i = 1,50 do
        for j = 1,50 do
            local r,g,b,a = img1:get(i,j)
            local v = 255/a

            img2:set(i,j,color(r,g,b,a))
            -- img2:set(i,j,color(r*v,g*v,b*v,a))
        end
    end
end

function draw()
    background(40, 40, 50)

    noSmooth()
    sprite(img1,WIDTH/4,HEIGHT/2,WIDTH/3)
    sprite(img2,WIDTH*3/4,HEIGHT/2,WIDTH/3)
end
Tagged:

Comments

  • Posts: 2,020

    Something to do with the pre multiplied alpha flag perhaps? If I recall, it is automatically set to true if you use image set, but perhaps you can override this?

  • Posts: 103

    You can set img2.premultiplied=true before drawing the image, but that only works in the example. Since I'm copying the data into the rects in the mesh, it saves the wrong value

  • Posts: 103

    Here's a better example of the code I'm using

    function setup()
        img1 = image(50,50)
        fill(0,35,255,127)
        setContext(img1)
        ellipse(25,25,50)
        setContext()
    
        m = mesh()
        tab = {}
        for i = 1,img1.width do
            tab[i] = {}
            for j = 1,img1.height do
                tab[i][j] = m:addRect(i,j,1,1)
                local r,g,b,a = img1:get(i,j)
                m:setRectColor(tab[i][j],color(r,g,b,a))
            end
        end
    
    end
    
    function draw()
        background(40, 40, 50)
    
        noSmooth()
        sprite(img1,WIDTH/4,HEIGHT/2,WIDTH/3)
        pushMatrix()
        translate(WIDTH*3/4-WIDTH/6,HEIGHT/2-WIDTH/6)
        scale(WIDTH/3/img1.width)
        m:draw()
        popMatrix()
    end
    
  • dave1707dave1707 Mod
    edited January 2016 Posts: 7,521

    @Dwins Add this background(255) after setContext(img1) in your code and see what you get.

        img1 = image(50,50)
        fill(0,35,255,127)
        setContext(img1)
        background(255)
        ellipse(25,25,50)
        setContext()
    
  • Posts: 103

    Sorry @dave1707 I don't think that solved the problem

  • dave1707dave1707 Mod
    edited January 2016 Posts: 7,521

    @Dwins I wasn't trying to solve the problem, I was just showing that adding a background color totally changes the color even though your original color hasn't changed.

Sign In or Register to comment.