问题,给你一张图像,只有个像素点,要求根据这几个点用OpenCV画出拟合直线

代码
import cv2
import numpy as np
path ="G:\python\OpenCV_learn\data_fitline.png"
img =cv2.imread(path)
sp=img.shape
print(sp[0],sp[1])//图像的长宽
lower= np.array([0,0,0])
upper=np.array([0,0,0])
mask=cv2.inRange(img,lower,upper)//这里感觉不太对,之后优化一下,但这样可以实现,这里先记一下,之后记得改!!
ret,xy= cv2.threshold(mask,1,255,cv2.THRESH_BINARY)
kernel = np.ones((5, 5), np.uint8)
dilation = cv2.dilate(xy, kernel, iterations=1)//创个kenel来腐蚀一下,这样好找
collector=[]
_, contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
boxes = [cv2.boundingRect(c) for c in contours]
for box in boxes:
x, y, w, h = box
cv2.rectangle(img, (x, y), (x+w, y+h), (153, 153, 0), 2)
collector.append([x,y])//刚好利用上面的rectangle 函数得到x,y 坐标,这里看有没有更好的解决办法,先记一下
dot_collector=np.array(collector)//因为要用fitline 函数就要用到点集,所以这里用append创一个
output = cv2.fitLine(dot_collector, cv2.DIST_L2, 0, 0.01, 0.01)
k=output[1]/output[0]
y=k*(0-output[2])+output[3]
x=(sp[1]-output[3])/k+output[2]//几个函数分别返回sinx,cosx ,x0,yo,刚好求斜率和直线经过的一点
print(x,y) //前面我们有了图像的大小,刚好可以求截距,这样有了两个点,就可以画直线了
ptStart = (0,y)
ptEnd = (x, sp[1])
point_color = (0, 255, 0)
thickness = 1
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)
cv2.imshow("anyway",dilation)
cv2.imshow("colin",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果
