Detect pixel color from Raster

Hi
I am trying to count the number of white pixels I have in a grayscale TIFF image, using JAI I get a buffered image then pass in a portion of the image (raster) to a method. This works fine for some of my images and not at all with others, I have, after lots of pain and suffering ive found out that in some of the images a white pixel is 0 while in others it is -1.
I am counting white pixels and considering all others black ...to allow bi-tonal and grayscale images alike. I am lost as far as these images are concerned ...my guess is that the info i need is in the sample model but i have spent more time researching the inner workings of image than the scope of my project requires already
so im hoping someone can help me out here ...all i wanna do is detect a white pixel in a raster (hopefully this is as easy as it sounds)
-Jerome BG

Well after doin a bunch of reading and investigative work I know way more about image rendering and visualization than I ever wanted to know. So I know that you cant determine the pixel's color without the ColorModel, but since I can convert grayscale images to bi-tonal i know all ill have is 0 or 1 ...I still dunno how to use the ColorModel to determine which is which, but its not so important since all my images have white as 0.
Any ways if anyone out there is as obtuse as my self just using:
myRaster.getSample(x,y,band)(only one band for bi-tonal images) you get the bit as an int.
If anyone knows how to determine how to find out rather white or black is 0 using the Raster and the ColorModel I would still like to know
-Jeorme BG

Similar Messages

  • Reading pixel color from Image?

    Hello frnds,
    I am making a project in which i have to upload Image, am trying to find color of each pixel in RGB format so that I can locate where my sprite begins in Image !!
    But I am not able to do so.. do I have to use PixelGrabber to do that? or should i use RGBImageFilter..!! I am new to java so if u can tell me how to use them, then It would be grateful.
    I want to scan whole image from left to right, Right to left, top to bottom and vice-versa. So that I can exactly tell at what pixel value sprite starts and ends.
    Please help me out. any sort of help will be useful for my project..
    Thanking you in advance.

    Image bufferImage;PixelGrabber pg1;
    public boolean fetchPixels(byte[] jpegData, int[] pixelData)
         try
              bufferImage = Toolkit.getDefaultToolkit().createImage(jpegData);
              // this may not be required unless asynchronous, but seems to do no harm
              MediaTracker mt = new MediaTracker(jcamData);
              mt.addImage(bufferImage, 0);
              try
                   mt.waitForID(0);
              catch(InterruptedException e)
                   e.printStackTrace();
              if(mt.isErrorAny()==true)
                   System.out.println("Exception fetchPixels "+"createImage failed");
                   // flush anything in bufferedImage
                   if(bufferImage!=null)bufferImage.flush();
                   return false;     // and pixelData not updated
              Thread.yield();
              pg1 = new PixelGrabber(bufferImage, 0, 0, camWidth, camHeight, pixelData, 0, camWidth);
              try{pg1.grabPixels();}catch(InterruptedException e){}
              Thread.yield();
              // flush bufferedImage as no longer needed, and so not to be in memory cache for next image load
              if(bufferImage!=null)
                   bufferImage.flush();               
         catch(Exception e){System.out.println("Exception fetchPixels "+e);}
         return true;
    }

  • Please Help Get a Color from Pixel !!!!

    Is anybody know how to get a Color from pixel.
    My program is not Full Screen .
    So i think Robot.getPixelColor() don't suitable.
    Please Help me!

    Robot.getPixelColor() will work fine, but the problem you will have is getting the mouse set to the correct location and getting your application to know where it is: you can do it with win32 calls and JNI. Here are a few that I have found helpful--they are in a VB format:
    Public Const CLR_INVALID = &HFFFF 'not a valid pixel
    Public Const MOUSE_MOVED = &H1
    Public Const MOUSEEVENTF_ABSOLUTE = &H8000 ' absolute move
    Public Const MOUSEEVENTF_LEFTDOWN = &H2 ' left button down
    Public Const MOUSEEVENTF_LEFTUP = &H4 ' left button up
    Public Const MOUSEEVENTF_RIGHTDOWN = &H8 ' right button down
    Public Const MOUSEEVENTF_RIGHTUP = &H10 ' right button up
    Public Const REQUEST_LEFT_CLICK = &H2D 'request left click "-"
    Public Const REQUEST_RIGHT_CLICK = &H2B 'request right click "+"
    Type POINTAPI
    x As Long
    y As Long
    End Type
    Type POINTSTRUCT
    hwnd As Long
    hdc As Long
    ptAbsolute As POINTAPI
    ptOrigin As POINTAPI
    ptLocal As POINTAPI
    ptColor As Long
    sType As String
    retMessage As Boolean
    End Type
    Declare Function GetCursorPos _
    Lib "user32" (ByRef lpPoint As POINTAPI) _
    As Long
    Declare Function SetCursorPos _
    Lib "user32" (ByVal x As Long, ByVal y As Long) _
    As Long
    Declare Sub mouse_event _
    Lib "user32" (ByVal dwFlags As Long, _
    ByVal dx As Long, _
    ByVal dy As Long, _
    ByVal cButtons As Long, _
    ByVal dwExtraInfo As Long)
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    Declare Function GetMessageExtraInfo Lib "user32" () As Long
    Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, _
    ByVal x As Long, _
    ByVal y As Long) As Long
    Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, _
    ByVal yPoint As Long) As Long
    Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
    Declare Function GetWindowOrgEx Lib "gdi32" (ByVal hdc As Long, _
    ByRef lpPoint As POINTAPI) As Long

  • Photoshop CS2: Get CMYK color from pixel?

    Hi, in Photoshop CS3 I can use colorSamplers to pick up a CMYK color from a pixel. But I haven't found anything in the CS2 scripting reference about that.
    I cannot use channels["cyan"].histogram, because I need the calculated %-value (0100) from Photoshop, not the color index number (0255).
    Example:
    A pixel was filled with 70% cyan, Photoshop uses internally 69,8% and that's the value I want to read through a script.
    Any suggestions? :-)

    [email protected] wrote:
    > Hi, in Photoshop CS3 I can use colorSamplers to pick up a CMYK color from a pixel. But I haven't found anything in the CS2 scripting reference about that.
    >
    > I cannot use channels["cyan"].histogram, because I need the calculated %-value (0100) from Photoshop, not the color index number (0255).
    >
    > Example:
    > A pixel was filled with 70% cyan, Photoshop uses internally 69,8% and that's the value I want to read through a script.
    >
    > Any suggestions? :-)
    Try this:
    var cyanPercent = (channels["cyan"].histogram/255) * 100;
    -X
    for photoshop scripting solutions of all sorts
    contact: [email protected]

  • Convert colour images to grayscale images & get pixel data from them

    Is the code below correct to convert colour images to grayscale images in Java?
    public void convertToGrayscale (String sourceName,String destName) throws Exception {
    JPEGImageDecoder decoder=JPEGCodec.createJPEGDecoder(new FileInputStream(sourceName));
    JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(new FileOutputStream(destName));
    BufferedImage sourceImg=decoder.decodeAsBufferedImage();
    BufferedImageOp op =new ColorConvertOp(
              ColorSpace.getInstance(ColorSpace.CS_GRAY),null);
         BufferedImage destImg = op.filter(sourceImg,null);
    encoder.encode(destImg);
    decoder = null;
    encoder = null;
    When I get grayscale images from the code below, I would like to access the pixels of those images. So I tried to do:
    byte[] dd=((DataBufferByte)mImage.getRaster().getDataBuffer()).getData();
    BUT the data result array is not 0-255. Could anyone suggest how to obtain pixel data from grayscale images?
    In case that my code shown is not correct or suitable, please give your advice. What I would like to do are in the steps as follows:
    1 change 100*70 jpeg-images to 100*70 grayscale images.
    2 create two dimensional array of pixel data (example [100][70]) from converted images. The number in the array should be between 0-255, right??? And 0 refers to black colour and 255 refers to white colour???
    I am confused about grayscale images. Please help.
    Thank you so much

    I am not sure i understand what is the problem exactly.
    Structure of DataBuffer is described by SampleModel used by same Raster
    object. E.g. it might be 1 byte per xipex or 4 bytes per pixel.
    In your example convertToGrayscale saves images to file as JPEG and
    it seems you later read it back. It is possible what image you read back
    is not greyscale but ARGB and data buffer has different format.
    Technically, if you just need level of grey you may simply
    call getRGB on your output image. Grey is uniform mix of R, G and B.
    Also, instead of ColorConverOp you may dimply create output image of
    grayscale type and draw your color input image with drawImage().
    If none of these helps please try to provide more details.

  • Magic Wand Selection Tool Fails to Operate on Precise Pixel Color

    I had an interesting thing happen with Photoshop CS5...  My Magic Wand tool got to where it wasn't selecting pixel colors based on the one under the tip of the tool when clicked.  It was selecting what seemed like similar colors, but its operation wasn't really predictable.
    It turns out that in a prior unrelated operation (days ago) I had changed the color picker to look at a very large number of pixels when sampling.
    Having chosen the above, the setting was sticky and modal (meaning it subsequently affected samples taken from then on by a variety of tools).
    I didn't think that this should affect subsequent samples taken with the Magic Wand tool.  I'm not sure this has always been the case, but it doesn't seem as though it should work this way.
    Notably I don't see any way, while the Magic Wand tool is active, that the above sample size can be changed.  Nor did Resetting the Magic Wand tool correct the situation.
    Should the previously selected color picker sample size actually affect the Magic Wand tool, or is this a case where someone at Adobe consolidated the pixel sampling logic a bit too aggressively?
    If the latter, here's an adage to post in the halls of Adobe Engineering:  "Make everything as simple as possible, but no simpler."
    -Noel

    Hm, appears to be an old issue:  http://forums.adobe.com/message/3226358
    What I can't fathom is that it's never bitten me before.  I do tend to leave the eyedropper on 1 x 1 pixels, but I occasionally do sample larger regions.
    -Noel

  • How to get max 5 color from image??

    I try to get max 5 color from image (ex. jpeg,gif) ,I use PixelGrabber
    it too slowly when i use large image,Please help me, to run more fast
    (other way PixelGrabber)
    best regard
    [email protected],[email protected]
    source below:
    public String generateColor(InputStream source,String filePath){
    BufferedImage image = null;
    String RGB = "";
    System.out.println("==generateColor==");
    try {
    image = ImageIO.read(source);
    catch (IOException ex1) {
    ex1.printStackTrace();
    //image.getGraphics().getColor().get
    // BufferedImage image2 = ImageIO.read(source);
    // image.getColorModel().getNumColorComponents()
    if(image.getColorModel() instanceof IndexColorModel) {
    IndexColorModel icm = (IndexColorModel)image.getColorModel();
    byte[][] data = new byte[3][icm.getMapSize()];
    int[] rgbB = new int[icm.getMapSize()];
    icm.getRGBs(rgbB);
    String dataHtm = "<HTML><table width=\"100\" border=\"0\"><tr>";
    for(int i = 0 ;i< rgbB.length;i++){
    int r = (rgbB[i] >> 16) & 0xff;
    int g = (rgbB[i] >> 8) & 0xff;
    int k = (rgbB) & 0xff;
    System.out.println("red:" + Integer.toHexString(r));
    System.out.println("green:" + Integer.toHexString(g));
    System.out.println("blue:" + Integer.toHexString(k));
    dataHtm = dataHtm + "<td width=\"10\" bgcolor=\"#" + Integer.toHexString(r)+Integer.toHexString(g)+Integer.toHexString(k);
    dataHtm = dataHtm + "\"> </td>";
    dataHtm = dataHtm + "</tr></table></HTML>";
    try {
    BufferedWriter out = new BufferedWriter(new FileWriter("c:\\23289207.html"));
    out.write(dataHtm);
    out.close();
    catch (IOException e) {
    e.printStackTrace();
    int w = image.getWidth();
    int h = image.getHeight();
    int[] pixels = new int[w*h];
    int[] pixs = new int[w*h];
    System.out.println("image width:"+w+"image hight:"+h+"image w*h:"+(w*h));
    Image img = Toolkit.getDefaultToolkit().getImage(filePath);
    PixelGrabber pg = new PixelGrabber(img, 0,0, w, h, pixels, 0, w);
    try {
    pg.grabPixels();
    catch (Exception x) {
    x.printStackTrace();
    String picColor = "";
    Stack stackColor = new Stack();
    Hashtable hashColor = new Hashtable();
    for (int i = 0; i < w * h; i++) {
    int rgb = pixels[i];
    int a = (rgb >> 24) & 0xff;
    int r = (rgb >> 16) & 0xff;
    int g = (rgb >> 8) & 0xff;
    int k = (rgb) & 0xff;
    i = i+1000;
    //System.out.println("i:" + i);
    picColor = convertToSring(r)+convertToSring(g)+convertToSring(k);
    stackColor.add(picColor);
    //System.out.println("picColor:"+picColor);
    // System.out.println("\n\n a:" + a);
    // System.out.println("red:" + r);
    // System.out.println("green:" + g);
    // System.out.println("blue:" + k);
    }//end for
    getMaxColor(stackColor);
    System.out.println("==generateColor==end\n\n");
    return null;

    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class HighFive
        private void examineColors(BufferedImage image)
            long start = System.currentTimeMillis();
            int w = image.getWidth(), h = image.getHeight();
            int[] rgbs = image.getRGB(0,0,w,h,null,0,w);
            findHighFive(rgbs);
            long end = System.currentTimeMillis();
            System.out.println("total time = " + (end - start)/1000.0 + " seconds");
        private void findHighFive(int[] colors)
            int[] uniqueColors = getUniqueColors(colors);
            int[] colorCounts  = getColorCounts(uniqueColors, colors);
            int[] highFive     = getHighFive(colorCounts);
            // for each value of highFive find index in colorCounts
            // and use this index to find color code in uniqueColors
            for(int j = 0; j < highFive.length; j++)
                int index = findIndexInArray(colorCounts, highFive[j]);
                Color color = new Color(uniqueColors[index]);
                String s = color.toString();
                s = s.substring(s.indexOf("["));
                System.out.println("color " + s + "  occurs " +
                                    highFive[j] + " times");
        private int[] getUniqueColors(int[] colors)
            // collect unique colors
            int[] uniqueColors = new int[colors.length];
            int count = 0;
            for(int j = 0; j < colors.length; j++)
                if(isUnique(uniqueColors, colors[j]))
                    uniqueColors[count++] = colors[j];
            // trim uniqueColors
            int[] temp = new int[count];
            System.arraycopy(uniqueColors, 0, temp, 0, count);
            uniqueColors = temp;
            return uniqueColors;
        private int[] getColorCounts(int[] uniqueColors, int[] colors)
            // count the occurance of each unique color in colors
            int[] colorCounts = new int[uniqueColors.length];
            for(int j = 0; j < colors.length; j++)
                int index = findIndexInArray(uniqueColors, colors[j]);
                colorCounts[index]++;
            return colorCounts;
        private int[] getHighFive(int[] colorCounts)
            // find five highest values in colorCounts
            int[] highFive = new int[5];
            int count = 0;
            for(int j = 0; j < highFive.length; j++)
                int max = Integer.MIN_VALUE;
                for(int k = 0; k < colorCounts.length; k++)
                    if(colorCounts[k] > max)
                        if(isUnique(highFive, colorCounts[k]))
                            max = colorCounts[k];
                            highFive[count] = colorCounts[k];
                count++;
            return highFive;
        private boolean isUnique(int[] n, int target)
            for(int j = 0; j < n.length; j++)
                if(n[j] == target)
                    return false;
            return true;
        private int findIndexInArray(int[] n, int target)
            for(int j = 0; j < n.length; j++)
                if(n[j] == target)
                    return j;
            return -1;
        public static void main(String[] args) throws IOException
            String path = "images/cougar.jpg";
            Object o = HighFive.class.getResource(path);
            BufferedImage image = ImageIO.read(((URL)o).openStream());
            new HighFive().examineColors(image);
    }

  • Skin colors from variables?

    My app is shaping up to use several skins.  Not a problem, but I'd like to have a way to reference a global variable for a color used in a skin.
    For example, if I have something like
         <!-- layer 3: title bar fill -->
         <s:Rect left="1" right="1" top="1" height="30">
            <s:fill>
            <s:LinearGradient rotation="90">
            <s:GradientEntry color="0xE8D8B4" alpha="1"/>
            <s:GradientEntry color="0xD3B36D" alpha="1"/>
            </s:LinearGradient>
            </s:fill>
         </s:Rect>
    I would like to set, in the main app, a pair of variables such as
    [Bindable] public var gradStart:String = "0xE8D8B4"
    and then use in the component for the gradient entry.
    Is this possible?  What's the syntax?

    I've never used getters and setters.  I will need to look into it.  Thanks.
    I tried using
    [Bindable]
    public var testColor:String = "0xff0000";
    in the main app and then:
    color="{FlexGlobals.topLevelApplication.testColor}" in the component.  It did work, surprisingly, except for a warning about not being able to detect changes to testColor.
    What I ulitmately need to do is to be able to have all these values in an XML file, load that into an XMLListCollection and then "assign" the colors from that.  What would be ideal is if I could do it right from the list, something like:
    [Bindable]
    public var styleList:XMLListCollection; // contains the xml data
    then
    color="{styleList.window[0].colorValue}"
    Any idea if something like this is feasible?

  • Get color from image

    Hey people, I'm new to Illustrator and have a question. I want to use a color from an image that I put into Illustrator.
    The exact things I did with the image are the following: copied it from Windows Photo Viewer into Illustrator, then put the 'cut out' effect on it, then copied it into a new Illustrator document that has a businesscard template and resized it fit the template's margins. Now I want to kind of 'enlengthen' the image by putting a square next to it. To make it look smooth, it has to have the same color as that side of the image of course. But that's my problem, I'm not able to select the color from the image and make a new color group with that specific color. The 'get color from selected artwork' button doensn't help much since I can't click it, for some reason the mouse turns into this 'can't click here' icon every time I move it on this button.
    Any help would be greatly appreciated!
    PS apologies for any unavoidable noobness

    To sample a color from a raster image, ShiftClick with the Eyedropper tool. (CS3)
    Always state what software version you are using.
    JET

  • Get color from paintPanel()

    I need a way to get the Color from a paint panel when the user clicks the mouse. I already have the mouse listener set up to return the co-ordinates within the paint panel.
    Could you suggest a class and method I could use, to get the color value from the paint panel.
    here's some of the code, so you know what i'm taking about
         public void mouseClicked (MouseEvent e)
                   System.out.println("the co-ordinates are "+ e.getX()+" "+e.getY());
              }

    There is no Image object there is only a paintPanel object.
    Doesn't seem to be a constructor for an image object in the Image Class.
    There must be an easier way of getting the pixel color for any given co-ordinates within the paintPanel object.

  • Get pixel color on screen

      What function do I use to get pixel color of screen
    ChangChiTheGraphics
    chang Chi

    Hello  C.H.Chi
    This code might solve your problem.
    public partial class Form1 : Form
    public Form1()
    InitializeComponent();
    Bitmap myBitmap;
    private void Form1_MouseMove(object sender, MouseEventArgs e)
    Color pixelColor = myBitmap.GetPixel(e.X, e.Y);
    this.Text = pixelColor.ToString();
    private void Form1_Load(object sender, EventArgs e)
    myBitmap = new Bitmap(Properties.Resources.Tulips);
    place a image in your resource file and access from their.
    Kindly mark as answer if found useful.

  • How can I change the background of a running webpage on my own. Example Facebook I want to change its backround color from white to black just in my view not for all

    How can I change the background of a running webpage on my own. Example Facebook I want to change its background color from white to black just in my view, not for all. Cause I really hate some site with white background because as I read for an hour it aches my eyes but not on those with darker background color.

    You can use the NoSquint extension to set font sizes (text/page zoom) and text colors on web pages.
    *NoSquint: https://addons.mozilla.org/firefox/addon/nosquint/

  • I cant seem to print in color from iphoto

    when ever i try to print from iphoto it only prints in color....what do i do?

    i cant seem to print in color from iphoto
    tdav18 wrote:
    when ever i try to print from iphoto it only prints in color....what do i do?
    Please restate your question - your title and   question are different - I have no idea what you want to do
    LN

  • Why am I unable to change text color from black in LR5 book module?

    Why am I unable to change text color from black in LR5 Book Module?

    I'm assuming you clicked on the color patch besides the word <Character> to open the color picker window.
    At the right side of this window there is a vertical bar that has 2 horizontal black lines at the bottom.
    This is actually a slider. Pull it upwards with the color picker and color will appear in the window.

  • How can i change my e-mail address color from blue to black when i send a new message

    How can i change my e-mail address color from blue to black when i send a new message

    Hi Steven, if you send to yourself does it come through blue?
    Is this in the Header or a Signature?

Maybe you are looking for

  • Since upgrading to 10.5.7, network "fades" out

    My trusty old G5 still works great for the tasks I require of it and has faithfully responded to every system upgrade until 10.5.7. When I first boot it up, my account is set to launch Camino (my "second" browser) with a special URL that tracks stats

  • Open my photos in CS6 and they don't show up (but show in layers palette)

    When I open a photo in Photoshop CS6 I can see the photo in the layers palette but it doesn't show up on my screen to work on. The only way I can get it to show up is if I act like I'm going to close Photoshop. Then when it asks if I want to close I

  • Nested Application Module State

    As I understand it Application Modules (AM) that are nested inherit the parent 'Transaction'. My question is do they inherit the Stateful/Stateless behaviour from the parent ?

  • Mail & Trash

    I found out that if you delete mail from your Inbox it actually just goes and sits in the trash. Even if you have the "Remove when removed from Inbox" selected in your account settings in your email. Has anyone else seen this? Is there an easier way

  • ORACLE_SID: set to?

    HI, The ORACLE_SID env variable: what is it for? what should it be set to? thanks null