preface

  • This article introduces how to use OpenCV to adjust the brightness and contrast of pictures

The theory of

Image transformation can be seen as follows: 1) Pixel transform — point operation, used to adjust image brightness and contrast, etc. 2) Neighborhood operation — region, It is used in image convolution, feature extraction, gradient calculation, pattern matching recognition, corner detection, blur, smooth and other operations to adjust image brightness and contrast belong to pixel transform – point operation G (I,j) = αf(I,j) + β two parameters α and β are called gain and bias parameters, which are used to control contrast and brightness respectively

The core idea

DST = Mat::zeros(src.size(), DST = Mat::zeros(src.size(), Saturate_cast (value) make sure the value ranges from 0 to 255. 5. Convert c++ image to UIImage

Code demo

One thing to note here is that you need to convert a 4-channel image to a 3-channel image,

/ / NS_INLINE CV ::Mat kFourChannelsBecomeThree(const CV ::Mat SRC){Mat DST; if (src.channels() == 4) { cv::cvtColor(src, dst, COLOR_RGBA2RGB); return dst; } return src; }Copy the code

If not converted, the resulting image display is incomplete

/* Adjust image brightness and contrast, contrast[0-100],luminance[0-2] */ - (UIImage*)kj_opencvChangeContrast:(int)contrast luminance:(double)luminance{ cv::Mat  src,dst; UIImageToMat(self,src,true); src = kFourChannelsBecomeThree(src); dst = Mat::zeros(src.size(), src.type()); int channels = src.channels(); for (int i = 0; i < src.rows; i++) { for (int j = 0; j < src.cols; j++) { if (channels == 3) {//rgb dst.at<Vec3b>(i, j)[0] = saturate_cast<uchar>(src.at<Vec3b>(i, j)[0] * luminance + contrast); dst.at<Vec3b>(i, j)[1] = saturate_cast<uchar>(src.at<Vec3b>(i, j)[1] * luminance + contrast); dst.at<Vec3b>(i, j)[2] = saturate_cast<uchar>(src.at<Vec3b>(i, j)[2] * luminance + contrast); }else if (channels == 1) {//gray dst.at<uchar>(i, j) = saturate_cast<uchar>(src.at<uchar>(i, j) * luminance + contrast); } } } return kMatToUIImage(dst); }Copy the code

rendering

Above is the original image

Serial article association

1, how to use OpenCV in iOS project 2, iOS using OpenCV to adjust the image brightness and contrast (1) 3, iOS using OpenCV image fusion (2) 4, iOS using OpenCV filter processing (3)

Then I will slowly added Opencv related articles, temporarily to common image processing and image algorithms encapsulation, friends in need can be to pod ‘KJExtensionHandler/Opencv’

How to use OpenCV in iOS project introduction to this end, there are related to supplement, writing articles is not easy, but also please click **Little stars* * portal