在图像上绘制一条曲线?

jaq*_*ues 5 python opencv numpy image-processing raspberry-pi

假设我有一张带有一些黑色像素的图像。我知道黑色像素的所有坐标,我正在寻找黄线。

给定:图像中黑色像素的坐标。

寻找:最适合黑色像素的黄色多项式

在此输入图像描述

import cv2
import numpy as np

cv2.imread("foo.jpg")
#search for the black pixels and save the coordinates.

#coordinates of all pixels (example)
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0]) 
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) 
z = np.polyfit(x, y, 2)
p = np.poly1d(z)
Run Code Online (Sandbox Code Playgroud)

如果我理解正确的话,现在我用 . 创建了一个多项式(图像上的黄线)np.poly1d()。但我怎样才能在我的 bgr_img 上绘制它呢?

编辑:

到目前为止,这是我的代码:

import cv2
import numpy as np

img = cv2.imread("white_foo.jpg") #1000x1000 pixel

#lets say these are my black pixels in a white image.
x = np.array([122, 224, 210, 350,  380,  250, 490, 623, 711, 819, 900])
y = np.array([536, 480, 390, 366, 270, 240, 180, 210, 280, 400, 501])

#calculate the coefficients.
z = np.polyfit(x, y, 2)
lspace = np.linspace(0, 1000, 100)

#here I want to draw the polynomial which I calculated with polyfit on my image

cv2.imshow("test", img)
cv2.waitKey(0)

Run Code Online (Sandbox Code Playgroud)

提前致谢

Nat*_*ate 5

快速谷歌出现:https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html#polylines

这是:Python中的Opencv折线函数抛出异常

无论如何,您需要在您感兴趣的点处计算多项式,然后适当地设置这些点的格式(折线希望它们位于 int32 容器中,格式类似于[[x_1, y_1], [x_2, y_2], ... , [x_n, y_n]])。然后只需调用该函数即可。

draw_x = lspace
draw_y = np.polyval(z, draw_x)   # evaluate the polynomial

draw_points = (np.asarray([draw_x, draw_y]).T).astype(np.int32)   # needs to be int32 and transposed

cv2.polylines(img, [draw_points], False, (0,0,0))  # args: image, points, closed, color
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述