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()

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

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值