Draw a curve line going through the blobs in OpenCV C++

夙愿已清 提交于 2019-12-11 03:37:21

问题


I am trying to draw a line that goes through the given blobs. The following is a given example

I want a curve line that goes through multiple blobs in horizontal direction as shown below.


回答1:


Just as example:

import cv2
import numpy as np

img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
(_, contours, _) = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# biggest area
target = max(contours, key=lambda x: cv2.contourArea(x))
cv2.drawContours(img, [target], -1, [0, 0, 255], -1) # debug
# just example of fitting
x = target[:, :, 0].flatten()
y = target[:, :, 1].flatten()
poly = np.poly1d(np.polyfit(x, y, 5))
for _x in range(min(x), max(x), 5): # too lazy for line/curve :)
    cv2.circle(img, (_x, int(poly(_x))), 3, [0, 255, 0])

cv2.imshow('result', img)
cv2.waitKey(0)




回答2:


Just for fun, and employing the Perl philosophy of TMTOWTDI ("There's More Than One Way to Do It)", I extracted all the white points of your contours into a file called points.dat and fed that into gnuplot to fit a curve, which gave me a formula for a best fit line of:

y=3.10869110524588e-07*x*x*x -0.000972406154863963*x*x + 0.861790477479291*x + 307.220397010312

And then I plotted that in red on your original contours using awk and ImageMagick.

#!/bin/bash
convert contours.jpg -colorspace gray -threshold 50% txt: | awk -F: '/white/{print $1}' | tr ',' ' ' > points.dat
{ echo 'f(x) = a*x**3 + b*x**2 + c*x + d'; \
  echo 'fit f(x) "points.dat" via a, b, c, d'; \
  echo 'print a,"*u^3 + ",b,"*u^2 + ",c,"*u + ",d'; \
} | gnuplot 2>&1 | tail -1    

awk 'BEGIN{
     for(x=0;x<1504;x++){
        y=3.10869110524588e-07*x*x*x -0.000972406154863963*x*x + 0.861790477479291*x + 307.220397010312
        y=int(y)
        print "point ",x,y
     }
     }' /dev/null > p.mvg

convert contours.jpg -draw @p.mvg z.png

The start of points.dat looks like this:

769 453
770 453
771 453
772 453
773 453
769 454
765 455
766 455
767 455
768 455
...
...

The start of p.mvg looks like this:

fill red
point  0 307
point  1 308
point  2 308
point  3 309
point  4 310
point  5 311
point  6 312
point  7 313
point  8 314
...
...


来源:https://stackoverflow.com/questions/44406469/draw-a-curve-line-going-through-the-blobs-in-opencv-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!