1 直接以灰度格式读取然后保存:
在imread函数中指定flag为IMREAD_GRAYSCALE
#include <stdio.h>#include <assert.h>#include <iostream>#include <opencv2/opencv.hpp>#include <opencv2/core.hpp>#include <opencv2/imgcodecs.hpp>#include <opencv2/highgui.hpp>using namespace cv;using namespace std;int main(int argc, char **argv) {Mat img = imread("a.jpg", IMREAD_GRAYSCALE);imwrite("out.jpg", img);return 0;}
2 使用cvtColor(src, dst, COLOR_BGR2GRAY):
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <sys/ioctl.h>#include <linux/videodev2.h>#include <string.h>#include <sys/mman.h>#include <assert.h>#include <opencv2/opencv.hpp>#include <opencv2/core.hpp>#include <opencv2/imgcodecs.hpp>#include <opencv2/highgui.hpp>using namespace std;using namespace cv;int main() {Mat img = imread("in.jpg", IMREAD_UNCHANGED);Mat img2;cvtColor(img, img2, COLOR_BGR2GRAY);imwrite("out.jpg", img2);return 0;}
3 将原图像的RGB值相加然后除以3。
以下是代码:
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <sys/ioctl.h>#include <linux/videodev2.h>#include <string.h>#include <sys/mman.h>#include <assert.h>#include <opencv2/opencv.hpp>#include <opencv2/core.hpp>#include <opencv2/imgcodecs.hpp>#include <opencv2/highgui.hpp>using namespace std;using namespace cv;int main(int argc, char **argv) {Mat img = imread("in.jpg", IMREAD_UNCHANGED);Mat gray(img.size(), CV_8UC1);uchar *data = gray.data;uchar *p = img.data;for (int i = 0; i < img.size().height * img.size().width; i++) {data[i] = (*(p++) + *(p++) + *(p++)) / 3;}imwrite("out.jpg", gray);return 0;}
如果觉得《在opencv中如何将一张彩色图像转换为灰度图像》对你有帮助,请点赞、收藏,并留下你的观点哦!