Image processing

This is the forum for miscellaneous technical/programming questions.

Moderator: 2ffat

Image processing

Postby rossco25 » Tue Dec 21, 2004 7:26 am

Hi there,
I am using Borland C++ Builder 4. I want to read in an image from a bitmap file, binarize the image and send the output to a new image for viewing. I know I have to use the TImage, TCanvas and TBitmap objects. Also I know I have to use the ScanLine method to read a row of pixels. I need to do this operation for my degree project. Any help would be much appreciated.
Thanks
Ross
rossco25
 

Postby Damon » Wed Dec 22, 2004 2:51 am

Hi Ross,
Working with 1-bpp bitmaps is a bit weird because you have adjust the individual bits within each byte, but here's some sample code to load a bitmap from a file, threshold that image, and then store the binary results in a 1-bpp TBitmap (held in a TPicture)...

Code: Select all
inline void SetBit(
   unsigned char* p_row,
   int x,
   bool val
  )
{
  if (val)
  {
    p_row[x / 8] |= (1 << (7 - (x % 8)));
  }
  else
  {
    p_row[x / 8] &= ~(1 << (7 - (x % 8)));
  }
}
//---------------------------------------------------------------------------


void __fastcall TForm1::Button1Click(TObject *Sender)
{
  // load the source bitmap
  std::auto_ptr<Graphics::TBitmap>
    SrcBitmap(new Graphics::TBitmap());
  SrcBitmap->LoadFromFile("c:/my_bitmap.bmp");
  SrcBitmap->PixelFormat = pf24bit; // assuming 24-bpp RGB
  int const cx = SrcBitmap->Width;
  int const cy = SrcBitmap->Height;

  // grab a reference to the destination bitmap,
  // set its pixel-format, and then resize it
  Graphics::TBitmap& DstBitmap = *Image1->Picture->Bitmap;
  DstBitmap.PixelFormat = pf1bit; // binary 
  DstBitmap.Width = cx;
  DstBitmap.Height = cy;

  // perform the image processing...
  unsigned char const T = 128; // threshold value
  for (int y = 0; y < cy; ++y)
  {
    // grab a pointer to the current row of the source bitmap
    RGBTRIPLE const* const p_src_row =
      static_cast<RGBTRIPLE*>(SrcBitmap->ScanLine[y]);
    // grab a pointer to the current row of the dest. bitmap
    unsigned char* const p_dst_row =
      static_cast<unsigned char*>(DstBitmap.ScanLine[y]);

    for (int x = 0; x < cx; ++x)
    {
      // threshold each pixel
      if (
        p_src_row[x].rgbtRed > T ||
        p_src_row[x].rgbtGreen > T ||
        p_src_row[x].rgbtBlue > T
        )
      {
        // set the bit of the destination bitmap
        // (i.e., turn the pixel "on")
        SetBit(p_dst_row, x, true);
      }
      else
      {
        // clear the bit of the destination bitmap
        // (i.e., turn the pixel "off")
        SetBit(p_dst_row, x, false);
      }
    }
  }
}


HTH,
Damon
User avatar
Damon
BCBJ Editor and Admin
BCBJ Editor and Admin
 
Posts: 285
Joined: Wed May 26, 2004 11:25 pm
Location: Stillwater, OK, USA


Return to Technical

Who is online

Users browsing this forum: No registered users and 15 guests