Chapter 4, Drawing, Filtering, and Transformation

  1. Write a program that draws a cross over the whole image, with a thickness of 3 pixels and a red color.
line(image,
Point(0,0),
Point(image.cols-1,image.rows-1),
Scalar(0,0,255),
3);
line(image,
Point(0,image.rows-1),
Point(image.cols-1,0),
Scalar(0,0,255),
3);
  1. Create a window with a trackbar to change the ksize of a medianBlur function. The range for the kszise value should be between 3 and 99.
Mat image;
int ksize = 3;
string window = "Image";
string trackbar = "ksize";
void onChange(int ksize, void*)
{
if(ksize %2 == 1)
{
medianBlur(image,
image,
ksize);
imshow(window, image);
}
}
int main()
{
image = imread("Test.png");
namedWindow(window);
createTrackbar(trackbar, window, &ksize, 99, onChange);
setTrackbarMin(trackbar, window, 3);
setTrackbarMax(trackbar, window, 99);
onChange(3, NULL);
waitKey();
}
  1. Perform a gradient morphological operation on an image, considering a kernel size of 7 and a rectangle morphological shape for the structuring element.
int ksize = 7;
morphologyEx(image,
result,
MORPH_GRADIENT,
getStructuringElement(MORPH_RECT,
Size(ksize,ksize)));

Here's an example:

  1. Using cvtColor, convert a color image to grayscale and make sure only the darkest 100 shades of gray are filtered out using the threshold function. Make sure the filtered pixels are set to white in the resulting image, and the rest of the pixels are set to black.
Mat imageGray;
cvtColor(image,
imageGray,
COLOR_BGR2GRAY);
threshold(imageGray,
result,
100,
255,
THRESH_BINARY_INV);

Here's an example:

  1. Use the remap function to resize an image to half of its original width and height, thus preserving the aspect ratio of the original image. Use a default border type for the extrapolation.
Mat mapX(image.size(), CV_32FC1);
Mat mapY(image.size(), CV_32FC1);
for(int i=0; i<image.rows; i++)
for(int j=0; j<image.cols; j++)
{
mapX.at<float>(i,j) = j*2.0;
mapY.at<float>(i,j) = i*2.0;
}
InterpolationFlags interpolation = INTER_LANCZOS4;
BorderTypes borderMode = BORDER_DEFAULT;
remap(image,
result,
mapX,
mapY,
interpolation,
borderMode);

Here's an example:

  1. a) Use colormaps to convert an image to grayscale. b) How about converting an image to grayscale and inverting its pixels at the same time?

a)

Mat userColor(256, 1, CV_8UC3);
for(int i=0; i<=255; i++)
userColor.at<Vec3b>(i,0) = Vec3b(i, i, i);
applyColorMap(image,
result,
userColor);

b)

Mat userColor(256, 1, CV_8UC3);
for(int i=0; i<=255; i++)
userColor.at<Vec3b>(i,0) = Vec3b(255-i, 255-i, 255-i);
applyColorMap(image,
result,
userColor);
  1. Did you read about perspective transformation functions? Which OpenCV function covers all similar transformations in one function?

The findHomography function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.233