การตัดสี

Posted by Undermine on 05:24

ตัวอย่างนี้แสดงวิธีการเบื้องต้น เพื่อแสดงวิธีการเข้าถึงข้อมูลแต่ละ pixel ของภาพ เพื่อทำการตัดสีตามค่าช่วงสีที่กำหนดไว้

#include
using namespace std;
#include
#include
#include
#define CAMERA_ID 0
#define ORG_IMAGE_DISPLAY "original image"
#define PROCESSED_IMAGE_DISPLAY "processed image"
// interested color value
#define RED_MIN 0
#define RED_MAX 255
#define GREEN_MIN 0
#define GREEN_MAX 100
#define BLUE_MIN 0
#define BLUE_MAX 100
// channel indices
#define BLUE_CH 0
#define GREEN_CH 1
#define RED_CH 2
int main( int argc, char **argv )
{
// create camera capture object.
CvCapture *pCapture = NULL;
pCapture = cvCreateCameraCapture( CAMERA_ID );
if ( pCapture == NULL )
{
cout << "ERROR: Failed to open camera" << endl;
return EXIT_FAILURE;
}
// create windows for displaying the captured image
// and the captured image.
cvNamedWindow( ORG_IMAGE_DISPLAY );
cvNamedWindow( PROCESSED_IMAGE_DISPLAY );
// capture, process, and display
// until user hit any key of the keyboard
IplImage *pOrgImage = NULL;
IplImage *pProcessedImage = NULL;
do
{
// release old image
// before creating a new one
if ( pProcessedImage != NULL )
{
cvReleaseImage( &pProcessedImage );
pProcessedImage = NULL;
}
// capture new image
pOrgImage = cvQueryFrame( pCapture );
// create image which has the same width, height, depth, and number of channels
// as the original image for put the result of processing.
// Then fill the created image with 0 value ( black image ).
pProcessedImage = cvCreateImage( cvSize( pOrgImage->width, pOrgImage->height ),
pOrgImage->depth, pOrgImage->nChannels );
cvSetZero( pProcessedImage );
// threshold the image by accessing all pixels of the image
for ( int y = 0; y < pOrgImage->height; y++ )
{
for ( int x = 0; x < pOrgImage->width; x++ )
{
int offset_x = x*pOrgImage->nChannels;
int offset_y = y*pOrgImage->widthStep;
unsigned char *pPixel = (unsigned char*)pOrgImage->imageData + (offset_x + offset_y);
unsigned char *pDstPixel = (unsigned char*)pProcessedImage->imageData + (offset_x + offset_y);
if ( ( pPixel[BLUE_CH] >= BLUE_MIN && pPixel[BLUE_CH] <= BLUE_MAX )
&& ( pPixel[GREEN_CH] >= GREEN_MIN && pPixel[GREEN_CH] <= GREEN_MAX )
&& ( pPixel[RED_CH] >= RED_MIN && pPixel[RED_CH] <= RED_MAX ) )
{
pDstPixel[RED_CH] = pDstPixel[GREEN_CH] = pDstPixel[BLUE_CH] = 255;
}
}
}
// display images
cvShowImage( ORG_IMAGE_DISPLAY, pOrgImage );
cvShowImage( PROCESSED_IMAGE_DISPLAY, pProcessedImage );
} while ( cvWaitKey( 1 ) == -1 );
// release old image
if ( pProcessedImage != NULL )
{
cvReleaseImage( &pProcessedImage );
pProcessedImage = NULL;
}
// before exiting the program,
// destroy the display windows and
// release the cameara capture object.
cvDestroyWindow( ORG_IMAGE_DISPLAY );
cvDestroyWindow( PROCESSED_IMAGE_DISPLAY );
cvReleaseCapture( &pCapture );
return 0;
}

0 comments:

แสดงความคิดเห็น