首页 > 解决方案 > 我们如何通过双线性插值生成新的采样点?

问题描述

我有一张灰度图片,我需要通过双线性插值生成新的采样点(图中红色圆圈)。是否有公式或函数来计算 python 中这些点的值?

在此处输入图像描述

标签: pythonopencv

解决方案


根据图表,它看起来不像双线性插值,它看起来像两个角度之间的平均值。

我不确定我的解决方案是否是您正在寻找的,但我认为它会给您带来领先...

我尝试通过使用三角法自动找到圆cv2.HoughCircles并标记位置x来解决它。y

该解决方案使用以下阶段:

  • 将图像转换为灰度和二进制。
  • 使用 查找圈子cv2.HoughCircles
  • 迭代圆,找到中心最靠近图像中心的圆。
  • 以 45 度为步长计算角度[0, 45, 90, 135...],命名它们alpha
    计算上述角度之间的角度[22.5, 67.5, 112.5...],命名它们beta
    我们真的不需要alpha计算beta
    这只是为了演示您应该做的那种插值。
  • 使用三角函数计算每个点的x, 。 用青色圆圈标记“alpha”点。 用黄色圆圈标记“beta”点。 您可以存储,的“beta”点 - 这些是您正在寻找的点。 y


    xy

这是代码:

import cv2
import numpy as np

# Read input imgae
img = cv2.imread('image.png')

# Convert to Grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Convert to binary image, and invert polarity
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

rows, cols = thresh.shape

circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=rows//8, param1=50, param2=60, minRadius=rows//8, maxRadius=rows//2)

# Find the circle with center closest to the center of the image
min_dist_from_center = 1e9
min_c = []
for c in circles[0,:]:
    # Euclidean distance from the center of circle to center of image
    dist_from_center = np.linalg.norm([c[0] - cols/2, c[1] - rows/2])
    if dist_from_center < min_dist_from_center:
        min_dist_from_center = dist_from_center
        min_c = c

c = min_c

# Draw circle for testing
cv2.circle(img, (c[0], c[1]), c[2], (0, 255, 0), 2)

# Array of angles in 45 degrees difference
alpha_arr = np.arange(0, 360+45, 45)  # [  0,  45,  90, 135, 180, 225, 270, 315, 360]
betta_arr = (alpha_arr[1:] + alpha_arr[0:-1])/2  # [ 22.5,  67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5] Points between alpha

# Compute x, y coordinates by angle and radius
r = c[2]
for alpha, beta in zip(alpha_arr[:-1], betta_arr):
    x = r*np.cos(np.deg2rad(alpha)) + c[0] # x = r*cos(alpha) + center_x
    y = r*np.sin(np.deg2rad(alpha)) + c[1] # y = r*sin(alpha) + center_y

    # Draw small cyan circle to mark alpha points
    cv2.circle(img, (int(x), int(y)), 12, (255, 255, 0), 3)

    x = r*np.cos(np.deg2rad(beta)) + c[0] # x = r*cos(alpha) + center_x
    y = r*np.sin(np.deg2rad(beta)) + c[1] # y = r*sin(alpha) + center_y

    # Draw small yellow circle to mark beta points
    cv2.circle(img, (int(x), int(y)), 10, (0, 255, 255), 3)


# Show images for testing
cv2.imshow('thresh', thresh)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:
在此处输入图像描述


推荐阅读