Opencv 最邻近插值

使用最邻近插值将图像放大1.5倍吧!

Opencv最近邻插值在图像放大时补充的像素取最临近的像素的值。由于方法简单,所以处理速度很快,但是放大图像画质劣化明显。

使用下面的公式放大图像吧!I’为放大后图像,I为放大前图像,a为放大率,方括号是四舍五入取整操作:

I'(x,y) = I([\frac{x}{a}], [\frac{y}{a}])

python实现:

import cv2
import numpy as np
import matplotlib.pyplot as plt


# Nereset Neighbor interpolation
def nn_interpolate(img, ax=1, ay=1):
    H, W, C = img.shape

    aH = int(ay * H)
    aW = int(ax * W)

    y = np.arange(aH).repeat(aW).reshape(aW, -1)
    x = np.tile(np.arange(aW), (aH, 1))
    y = np.round(y / ay).astype(np.int)
    x = np.round(x / ax).astype(np.int)

    out = img[y,x]

    out = out.astype(np.uint8)

    return out


# Read image
img = cv2.imread("imori.jpg").astype(np.float)

# Nearest Neighbor
out = nn_interpolate(img, ax=1.5, ay=1.5)

# Save result
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)

c++实现:

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <math.h>


// nearest nieghbor
cv::Mat nearest_neighbor(cv::Mat img, double rx, double ry){
  // get height and width
  int width = img.cols;
  int height = img.rows;
  int channel = img.channels();


  // get resized shape
  int resized_width = (int)(width * rx);
  int resized_height = (int)(height * ry);
  int x_before, y_before;

  // output image
  cv::Mat out = cv::Mat::zeros(resized_height, resized_width, CV_8UC3);

  // nearest neighbor interpolation
  for (int y = 0; y < resized_height; y++){
    y_before = (int)round(y / ry);
    y_before = fmin(y_before, height - 1);

    for (int x = 0; x < resized_width; x++){
      x_before = (int)round(x / rx);
      x_before = fmin(x_before, width - 1);

      // assign pixel to new position
      for (int c = 0; c < channel; c++){
          out.at<cv::Vec3b>(y, x)[c] = img.at<cv::Vec3b>(y_before, x_before)[c];
      }
    }
  }

  return out;
}


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

  // nearest neighbor
  cv::Mat out = nearest_neighbor(img, 1.5, 1.5);

  //cv::imwrite("out.jpg", out);
  cv::imshow("answer", out);
  cv::waitKey(0);
  cv::destroyAllWindows();

  return 0;
}

输入:

Opencv 最邻近插值

输出:

Opencv 最邻近插值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程