opencv 检测图像中的点,并拟合直线 --python实现

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

原图像

代码

import cv2
import numpy as np
path ="G:\python\OpenCV_learn\data_fitline.png"
img =cv2.imread(path)#导入并显示图像
sp=img.shape#获得图像size
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:
    #cv2.boundingRect()返回轮廓矩阵的坐标值,四个值为x, y, w, h, 其中x, y为左上角坐标,w,h为矩阵的宽和高
    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) # BGR
thickness = 1
lineType = 4
cv2.line(img, ptStart, ptEnd, point_color, thickness, lineType)

# for c in xy :
#     print(c)
#     cv2.circle(img=img, center=(int(c[1]), int(c[0])), radius=1, color=(0, 215, 255), thickness=1)#现在可以找到所有的像素了

cv2.imshow("anyway",dilation)
cv2.imshow("colin",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果

结果

  • 3
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值