码迷,mamicode.com
首页 > 其他好文 > 详细

图像处理100问——1.通道交换

时间:2020-01-06 00:37:41      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:color   port   class   pen   imshow   iostream   family   ace   处理   

任务:读取图像将RGB通道转换为BGR通道

代码:

python

import cv2

# function: BGR -> RGB
def BGR2RGB(img):
    b = img[:, :, 0].copy()
    g = img[:, :, 1].copy()
    r = img[:, :, 2].copy()

    # RGB > BGR
    img[:, :, 0] = r
    img[:, :, 1] = g
    img[:, :, 2] = b

    return img


# Read image
img = cv2.imread("./imgs/lena.jpg")

# BGR -> RGB
img = BGR2RGB(img)

# Save result
cv2.imshow("result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

C++

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std:
using namespace cv;

// Channel swap
Mat channel_swap(Mat img){
  // get height and width
  int width = img.cols;
  int height = img.rows;

  // prepare output
  Mat out = Mat::zeros(height, width, CV_8UC3);

  // each y, x
  for (int y = 0; y < height; y++){
    for (int x = 0; x < width; x++){
      // R -> B
      out.at<Vec3b>(y, x)[0] = img.at<Vec3b>(y, x)[2];
      // B -> R
      out.at<Vec3b>(y, x)[2] = img.at<Vec3b>(y, x)[0];
      // G -> G
      out.at<Vec3b>(y, x)[1] = img.at<Vec3b>(y, x)[1];
    }
  }

  return out;
}


int main(int argc, const char* argv[]){
  // read image
  Mat img = imread("./imgs/lena.jpg", IMREAD_COLOR);

  // channel swap
  Mat out = channel_swap(img);

  imshow("sample", out);
  waitKey(0);
  destroyAllWindows();

  return 0;
}

  

图像处理100问——1.通道交换

标签:color   port   class   pen   imshow   iostream   family   ace   处理   

原文地址:https://www.cnblogs.com/costanza/p/12154354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!