繁体   English   中英

在 python 中使用最近邻的仿射变换

[英]affine transformation using nearest neighbor in python

我想进行仿射变换,然后使用最近邻插值,同时保持输入和 output 图像的相同尺寸。 例如,我使用缩放变换 T= [[2,0,0],[0,2,0],[0,0,1]]。 知道如何用最近的邻居填充黑色像素吗? 我试着给他们邻居强度的最小值。 例如。 如果一个像素有邻居[55,22,44,11,22,55,23,231],我给它最小强度的值:11。但结果并不清楚..

import numpy as np
from matplotlib import pyplot as plt

#Importing the original image and init the output image
img = plt.imread('/home/left/Desktop/computerVision/SET1/brain0030slice150_101x101.png',0)
outImg = np.zeros_like(img)

# Dimensions of the input image and output image (the same dimensions)
(width , height) = (img.shape[0], img.shape[1])

# Initialize the transformation matrix
T = np.array([[2,0,0], [0,2,0], [0,0,1]])

# Make an array with input image (x,y) coordinations and add [0 0 ... 1] row
coords = np.indices((width, height), 'uint8').reshape(2, -1)
coords = np.vstack((coords, np.zeros(coords.shape[1], 'uint8')))

output = T @ coords

# Arrays of x and y coordinations of the output image within the image dimensions
x_array, y_array = output[0] ,output[1]
indices = np.where((x_array >= 0) & (x_array < width) & (y_array >= 0) & (y_array < height))

# Final coordinations of the output image
fx, fy = x_array[indices], y_array[indices]

# Final output image after the affine transformation
outImg[fx, fy] = img[fx, fy]

输入图像为:

在此处输入图像描述

缩放后的output图像为:

在此处输入图像描述

那么你可以简单地使用 opencv 调整 function

import cv2 
new_image = cv2.resize(image, new_dim, interpolation=cv.INTER_AREA)

它会调整大小并填充一个 go 中的空像素

更多关于 cv2.resize

如果您需要手动执行此操作,那么您可以简单地检测调整大小图像中的暗像素并将其值更改为 4 个相邻像素的平均值(例如 - 这取决于您所需的算法)请参阅:近邻、双线性、双三次等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM