OpenCV-图像取反

对图像进行取反,分为灰度和彩色两种取反,代码写的很差,抱歉。
C++:

#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;

int main(int argc, char*argv[])
{
	//加载图像
	Mat img, gray_image,dst;
	img = imread("D:/mouse.jpg");
	//判断图像是否导入成功
	if (img.empty())
	{
		cout << "加载失败" << endl;
		return -1;
	}
	//显示图像
	namedWindow("original image", WINDOW_AUTOSIZE);
	imshow("original image", img);
	//转换灰度图像
	cvtColor(img, gray_image, COLOR_BGR2GRAY);
	//获取灰度图像宽度和高度
	int width = gray_image.cols;
	int height = gray_image.rows;
	//遍历像素值(单通道)
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			int gray = gray_image.at<uchar>(row, col);
			gray_image.at<uchar>(row, col) = 255 - gray;	//图像取反
		};
	};
	namedWindow("inv_gray_image", WINDOW_AUTOSIZE);
	imshow("inv_gray_image", gray_image);
	
	//多通道
	dst.create(img.size(), img.type());
	int widths = img.cols;
	int heights = img.rows;
	int td = img.channels();
	for (int row = 0; row < heights; row++)
	{
		for (int col = 0; col < widths; col++)
		{
			int B = img.at<Vec3b>(row, col)[0];
			int G = img.at<Vec3b>(row, col)[1];
			int R = img.at<Vec3b>(row, col)[2];
			dst.at<Vec3b>(row, col)[0] = 255 - B;
			dst.at<Vec3b>(row, col)[1] = 255 - G;
			dst.at<Vec3b>(row, col)[2] = 255 - R;
		};

	};
	namedWindow("inv_rgb_image", WINDOW_AUTOSIZE);
	imshow("inv_rgb_image", dst);
	waitKey(0);
	return 0;
};


Python:

import cv2 as cv
import numpy as np

##读取图像
img = cv.imread('D:/mouse.jpg')
cv.imshow("original image",img)
##读取图像高宽和通道数
h,w,c=img.shape
##创建两个空图像分别为灰度和RGB反图像准备
gray_image=np.zeros((h,w,1),dtype=np.uint8)  #float类型取值范围 :-1 到1 或者 0到1
rgb_image=np.zeros(img.shape,dtype=np.uint8)  # uint8类型取值范围:0到255
#灰度图像取反
for r in range(h):
    for c in range(w):
        gray_image[r, c] = 0.3 * img[r, c][0] + 0.11 * img[r, c][1] + 0.59 * img[r, c][2]
        gray_image[r,c]=255-gray_image[r,c]
cv.imshow("gray image",gray_image)
#彩色图像取反
for r in range(h):
    for c in range(w):
        rgb_image[r,c]=(255-img[r,c][0],255-img[r,c][1],255-img[r,c][2])

cv.imshow("rgb image",rgb_image)
cv.waitKey(0)
cv.destroyAllWindows()

显示结果:
在这里插入图片描述

posted @ 2020-03-17 17:18  code_witness  阅读(301)  评论(0)    收藏  举报