How to use OPENCV to convert color images to grayscale with only 0 and 255 pixel values?

Source: Internet
Author: User
Tags polyline

Category: OpenCV

"Q1" how to convert a color picture to a grayscale with a pixel value of only 0 and 255 with OPENCV?

Grayscale, iplimage* pImg = Cvloadimage ("C:\\1.bmp", 0); So the image has been grayscale and then called  cvthreshold(image, image, 255, cv_thresh_binary); Yes, 125 there is the threshold you use, This is the simplest two value, you have to use Ostu, or other high-level, you have to write your own function

Truncate values above 100.
Cvthreshold(S, DST, 255, cv_thresh_trunc );//truncate a pixel value greater than 100, greater than 100 is 255, not greater than 100 is the original value

"Q2" Cvline Draw straight Line

Cvscalar color = Cv_rgb (50,0,250);
Cvline (IMG1, p1, Q1, color, 1, CV_AA, 0);
Cvline (IMG1, p2, q2, color, 1, CV_AA, 0);
Cvline (IMG1, p1, p2, color, 1, CV_AA, 0);
Cvline (IMG1, Q1, Q2, color, 1, CV_AA, 0);

Or

Cvline (Image,epipolarlinepoint1,epipolarlinepoint2,cv_rgb (0,255,0));

Cv::line

CV_RGB Create a color value. #define CV_RGB (R, G, b) [edit] Cvscalar ((b), (g), (R)) line draws a segment that connects two points void cvline (cvarr* img, Cvpoint pt1 , Cvpoint pt2, cvscalar color, int thickness=1, int line_type=8, int shift=0); IMG image. PT1 the first endpoint of a segment. Pt2 the second endpoint of a segment. The color of the color segment. Thickness the thickness of the segment. The type of the Line_type segment. 8 (or 0)-8-connected line (8 adjacency) connector. 4-4-connected Line (4 adjacency) connector. cv_aa-antialiased lines. The number of decimal places for the shift coordinate point. The Cvline function draws a segment between point 1 and point 2 in the image. The segment is cropped by the image or the rectangle of interest (ROI rectangle). For non-antialiasing lines with integer coordinates, use the 8-connection or 4-connection Bresenham algorithm. The end is rounded when you draw a thick outline. Draw antialiased lines using Gaussian filtering. To specify the segment color, users can use the macro Cv_rgb (R, G, b).

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++

How to use the Cvloadimage function

Four, image processing

1, memory allocation and release of the image

(1) Allocate memory to a new image:

iplimage* cvcreateimage (cvsize size, int depth, int channels);

Size:cvsize (Width,height);

Depth: Pixel depth: ipl_depth_8u, ipl_depth_8s, ipl_depth_16u,

Ipl_depth_16s, Ipl_depth_32s, ipl_depth_32f, ipl_depth_64f

Channels: Number of pixel channels. Can be 1, 2, 3 or 4.

Each channel is staggered. A color image is arranged in the following format:

B0 G0 r0 B1 g1 R1 ...

Example:

Allocate a 1-channel byte image
iplimage* img1=cvcreateimage (Cvsize (640,480), ipl_depth_8u,1);

Allocate a 3-channel float image
iplimage* img2=cvcreateimage (Cvsize (640,480), ipl_depth_32f,3);


(2) Release the Image:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_8u,1);
Cvreleaseimage (&IMG);


(3) Copy Image:

iplimage* img1=cvcreateimage (Cvsize (640,480), ipl_depth_8u,1);
Iplimage* Img2;
Img2=cvcloneimage (IMG1); Note the images obtained through Cvcloneimage
Also use Cvreleaseimage release, otherwise prone to memory leaks


(4) Set/Get ROI for area of interest:

void Cvsetimageroi (iplimage* image, Cvrect rect);
void Cvresetimageroi (iplimage* image);
Cvrect Cvgetimageroi (const iplimage* image);

Most OPENCV functions support ROI.

(5) Set/get channel of interest COI:

void Cvsetimagecoi (iplimage* image, int COI); 0=all
int Cvgetimagecoi (const iplimage* image);

Most OPENCV functions do not support COI.

2. Image reading and writing

(1) Read the image from the file:

Iplimage* img=0;
Img=cvloadimage (FileName);
if (!img) printf ("Could Not load image file:%s\n", fileName);

Supported image formats: BMP, DIB, JPEG, JPG, JPE, PNG, PBM, PGM, PPM,
SR, RAS, TIFF, TIF

OpenCV By default casts a read-in image into a three-channel color image. However, you can modify the read-in method as follows:

Img=cvloadimage (Filename,flag);

Flag: >0 casts the read-in image into a three-channel color image
=0 casts the read-in image into a single-channel grayscale image
<0 reads the same number of image channels as the file being read in.


(2) Save Image:

if (!cvsaveimage (outfilename,img)) printf ("Could not Save:%s\n", outfilename);

The saved image format is determined by the extension in Outfilename.

3. Accessing image pixels

(1) Suppose you want to access the pixels of the K-channel, line I, Column J.

(2) Indirect access: (Universal, but inefficient, access to images in any format)

* For single-channel byte images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_8u,1);
Cvscalar s;
S=CVGET2D (IMG,I,J); Get the (i,j) pixel value
printf ("intensity=%f\n", s.val[0]);
s.val[0]=111;
CVSET2D (img,i,j,s); Set the (I,J) pixel value

* For multi-channel byte/floating-point images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_32f,3);
Cvscalar s;
S=CVGET2D (IMG,I,J); Get the (i,j) pixel value
printf ("B=%f, G=%f, r=%f\n", s.val[0],s.val[1],s.val[2]);
s.val[0]=111;
s.val[1]=111;
s.val[2]=111;
CVSET2D (img,i,j,s); Set the (I,J) pixel value


(3) Direct access: (High efficiency, but error prone)

* For single-channel byte images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_8u,1);
((Uchar *) (Img->imagedata + i*img->widthstep)) [j]=111;

* For multi-channel byte images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_8u,3);
((Uchar *) (Img->imagedata + i*img->widthstep)) [J*img->nchannels + 0]=111; B
((Uchar *) (Img->imagedata + i*img->widthstep)) [J*img->nchannels + 1]=112; G
((Uchar *) (Img->imagedata + i*img->widthstep)) [J*img->nchannels + 2]=113; R

* For multi-channel floating-point images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_32f,3);
(float *) (img->imagedata + i*img->widthstep)) [J*img->nchannels + 0]=111; B
(float *) (img->imagedata + i*img->widthstep)) [J*img->nchannels + 1]=112; G
(float *) (img->imagedata + i*img->widthstep)) [J*img->nchannels + 2]=113; R


(4) Direct pointer-based access: (Simple and efficient)

* For single-channel byte images:

iplimage* img = cvcreateimage (cvsize (640,480), ipl_depth_8u,1);
int height = img->height;
int width = img->width;
int step = img->widthstep/sizeof (Uchar);
uchar* data = (UCHAR *) img->imagedata;
DATA[I*STEP+J] = 111;

* For multi-channel byte images:

iplimage* img = cvcreateimage (cvsize (640,480), ipl_depth_8u,3);
int height = img->height;
int width = img->width;
int step = img->widthstep/sizeof (Uchar);
int channels = img->nchannels;
uchar* data = (UCHAR *) img->imagedata;
DATA[I*STEP+J*CHANNELS+K] = 111;

* For multi-channel floating-point images (assuming that the image data is in 4-byte (32-bit) line alignment):

iplimage* img = cvcreateimage (cvsize (640,480), ipl_depth_32f,3);
int height = img->height;
int width = img->width;
int step = img->widthstep/sizeof (float);
int channels = img->nchannels;
float * data = (FLOAT *) img->imagedata;
DATA[I*STEP+J*CHANNELS+K] = 111;


(5) Direct access based on C + + wrapper: (Simpler and more efficient)

* First define a C + + wrapper ' image ' and then define different types of images based on the image:

Template<class t> class Image
{
  private:
  iplimage* IMGP;
  public:
  image (iplimage* img=0) {imgp=img;}
  ~image () {imgp=0;}
  void operator= (iplimage* img) {imgp=img;}
  inline t* operator[] (const int rowindx) {
    return ((T *) (Imgp->imagedata + Rowindx*imgp->widthstep));}
}; &NBSP;
 
typedef struct{
  unsigned char b,g,r;
} rgbpixel; 
 
typedef struct{
  float b,g,r;
} rgbpixelfloat; 
 
typedef image<rgbpixel>        Rgbimage;
typedef image<rgbpixelfloat>  rgbimagefloat;
typedef image<unsigned char>  bwimage;
typedef image<float>          bwimagefloat;

* For single-channel byte images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_8u,1);
Bwimage ImgA (IMG);
IMGA[I][J] = 111;

* For multi-channel byte images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_8u,3);
Rgbimage ImgA (IMG);
IMGA[I][J].B = 111;
IMGA[I][J].G = 111;
IMGA[I][J].R = 111;

* For multi-channel floating-point images:

iplimage* img=cvcreateimage (Cvsize (640,480), ipl_depth_32f,3);
Rgbimagefloat ImgA (IMG);
IMGA[I][J].B = 111;
IMGA[I][J].G = 111;
IMGA[I][J].R = 111;


4. Image conversion

(1) Grayscale-color conversion for byte-type images:

Cvconvertimage (SRC, DST, flags=0);

src = float/byte grayscale/color image
DST = byte Grayscale/color image
Flags = Cv_cvtimg_flip (flip image vertically)
CV_CVTIMG_SWAP_RB (Displacement R and B channels)


(2) Grayscale image with color image:

Using the OpenCV conversion:
Cvcvtcolor (Cimg,gimg,cv_bgr2gray); Cimg-Gimg

Using a direct conversion:
for (i=0;i<cimg->height;i++) for (j=0;j<cimg->width;j++)
Gimga[i][j]= (Uchar) (cimga[i][j].b*0.114 +
cimga[i][j].g*0.587 +
cimga[i][j].r*0.299);


(3) Conversion between different color spaces:

Cvcvtcolor (Src,dst,code); DST, SRC

Code = cv_<x>2<y>
<X>/<Y> = RGB, BGR, GRAY, HSV, YCRCB, XYZ, Lab, Luv, HLS

e.g.: Cv_bgr2gray, CV_BGR2HSV, Cv_bgr2lab

5. Drawing Instructions

(1) Draw the rectangle:

Draws a rectangle between the points (100,100) and (200,200), with a red edge and a width of 1
Cvrectangle (IMG, Cvpoint (100,100), Cvpoint (200,200), Cvscalar (255,0,0), 1);


(2) Draw the circle:

The center point is (100,100) and the radius is 20. Circular green, Width 1
Cvcircle (IMG, Cvpoint (100,100), Cvscalar (0,255,0), 1);


(3) Draw the segment:

Between (100,100) and (200,200), the line width is 1 of the Green Line segment
Cvline (IMG, Cvpoint (100,100), Cvpoint (200,200), Cvscalar (0,255,0), 1);


(4) Draw a set of segments:

Cvpoint curve1[]={10,10, 10,100, 100,100, 100,10};
Cvpoint curve2[]={30,30, 30,130, 130,130, 130, 30, 150,10};
cvpoint* curvearr[2]={curve1, curve2};
int ncurvepts[2]={4,5};
int ncurves=2;
int iscurveclosed=1;
int linewidth=1;

Cvpolyline (Img,curvearr,ncurvepts,ncurves,iscurveclosed,cvscalar (0,255,255), linewidth);

void Cvpolyline (cvarr* img, cvpoint** pts, int* npts, int contours, int is_closed,
Cvscalar color, int thickness=1, int line_type=8, int shift=0);
IMG image.
An array of vertex pointers for the PTS polyline.
An array of fixed-point numbers for npts polylines. It can also be thought of as the size of the PTS pointer array
The number of segments of the contours polyline.
Is_closed Indicates whether the polygon is closed. If closed, the function connects the starting and ending points.
The color of a color polyline.
Thickness the thickness of the line.
The type of the Line_type segment. See Cvline.
The number of decimal places for the shift vertex


(5) Draw a set of filled-color polygons:

Cvfillpoly (Img,curvearr,ncurvepts,ncurves,cvscalar (0,255,255));

The Cvfillpoly is used to fill a single area bounded by a polygon profile. Functions can populate complex areas, such as vulnerable areas and areas with intersections, and so on.
void Cvfillpoly (cvarr* img, cvpoint** pts, int* npts, int contours,cvscalar color, int line_type=8, int shift=0);
IMG image.
The PTS pointer to an array of polygons.
An array of the number of vertices of the npts polygon.
Contours the number of segments that make up the filled area.
The color of the color polygon.
Line_type the type of line that makes up the polygon.
The number of decimal places in the shift vertex coordinate.


(6) Text annotation:

Cvfont font;
Double hscale=1.0;
Double vscale=1.0;
int linewidth=1;
Cvinitfont (&font,cv_font_hershey_simplex| Cv_font_italic, Hscale,vscale,0,linewidth);

Cvputtext (IMG, "My comment", Cvpoint (200,400), &font, Cvscalar (255,255,0));

Other available font types are: Cv_font_hershey_simplex, Cv_font_hershey_plain, Cv_font_hershey_duplex, Cv_font_hershey_complex, CV_ Font_hershey_triplex, Cv_font_hershey_complex_small, Cv_font_hershey_script_simplex, CV_FONT_HERSHEY_SCRIPT_ COMPLEX,

Reference/////////////////

Cvloadimage (filename,-1); Default number of original channels to read images

Cvloadimage (filename, 0); Forced conversion read image as grayscale graph

Cvloadimage (filename, 1); Reading a color map

Example: Casting a read-in image to a grayscale image display

#include

#include <cv.h>

int main (int argc, char **argv)

{

if (argc! = 2)

return-1;

  

Iplimage *img = Cvloadimage (argv[1], 0);

Cvnamedwindow ("example");

Cvshowimage ("Example", IMG);

Cvwaitkey (0);

Cvreleaseimage (&IMG);

Cvdestroywindow ("example");

return 0;

}

How to use OPENCV to convert color images to grayscale with only 0 and 255 pixel values?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.