\section{Basic operations with images} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % C++ % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \ifCpp \subsection{Input/Output} Load an image from a file: \begin{lstlisting} Mat img = imread(filename); \end{lstlisting} If you read a jpg file, a 3 channel image is created by default. If you need a grayscale image, use: \begin{lstlisting} Mat img = imread(filename, 0); \end{lstlisting} Save an image to a file: \begin{lstlisting} Mat img = imwrite(filename); \end{lstlisting} \subsection{Accessing pixel intensity values} In order to get pixel intensity value, you have to know the type of an image and the number of channels. Here is an example for a single channel grey scale image (type 8UC1) and pixel coordinates x and y: \begin{lstlisting} Scalar intensity = img.at(x, y); \end{lstlisting} \texttt{intensity.val[0]} contains a value from 0 to 255. Now let us consider a 3 channel image with \texttt{bgr} color ordering (the default format returned by imread): \begin{lstlisting} Vec3b intensity = img.at(x, y); uchar blue = intensity.val[0]; uchar green = intensity.val[1]; uchar red = intensity.val[2]; \end{lstlisting} You can use the same method for floating-point images (for example, you can get such an image by running Sobel on a 3 channel image): \begin{lstlisting} Vec3f intensity = img.at(x, y); float blue = intensity.val[0]; float green = intensity.val[1]; float red = intensity.val[2]; \end{lstlisting} The same method can be used to change pixel intensities: \begin{lstlisting} img.at(x, y) = 128; \end{lstlisting} There are functions in OpenCV, especially from calib3d module, such as \texttt{projectPoints}, that take an array of 2D or 3D points in the form of \texttt{Mat}. Matrix should contain exactly one column, each row corresponds to a point, matrix type should be 32FC2 or 32FC3 correspondingly. Such a matrix can be easily constructed from std::vector: \begin{lstlisting} vector points; //... fill the array Mat _points = Mat(points); \end{lstlisting} One can access a point in this matrix using the same method \texttt{Mat::at}: \begin{lstlisting} Point2f point = _points.at(i, 0); \end{lstlisting} \fi