opencv进行简单的图像处理

涉及到了opencv里的一些基础图像处理知识

要求:将图片中的纱线中心定位出来,并且寻找中心的拟合直线。
已知图片:
在这里插入图片描述

代码:


```python
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('C:/Users/28986/Desktop/1_1.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
ret, thresh = cv2.threshold(img_gray, 130, 255, cv2.THRESH_BINARY)
# cv2.imshow('thresh', thresh)
# cv2.imwrite('2_1.jpg', thresh)
# cv2.waitKey(0)

# 寻找二值化图中的轮廓
image, contours, hierarchy = cv2.findContours(
    thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 3.绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
print(len(contours))
# cv2.imshow('contours', img)
# cv2.imwrite('contours.jpg', img)
# cv2.waitKey(0)

loc = [] # 坐标
for c in contours:
    area = cv2.contourArea(c)
    if area>10000:
        M = cv2.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        loc.append([cX,cY])
        cv2.circle(img, (cX, cY), 15, (0, 0, 255), -1)
        cv2.imwrite('contours_1.jpg', img)
loc = np.array(loc)
print(loc)

output = cv2.fitLine(loc, cv2.DIST_L2, 0, 0.01, 0.01)
k = output[1] / output[0]
b = output[3] - k * output[2]

cv2.line(img, (0, b), (2780, k*2780+b), (255, 0, 0), 5)
cv2.imwrite('finally.jpg', img)


x = np.arange(0,2780,1)
y = k*x+b
plt.xlim(0,2780)
plt.ylim(0, 2661)
plt.grid(alpha=0.6,linestyle=':')
plt.xticks([])
plt.yticks([])
plt.plot(x,y)
plt.plot([2690,2489,2258,1814,1617,1433,1168,965,691,481,322,17],[1347,1342,1344,1369,1321,1344,1341,1366,1337,1326,1314,1302],'ro')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
处理结果图
求质心的直线拟合:![在这里插入图片描述](https://img-blog.csdnimg.cn/20210308215559712.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01TRE5fSQ==,size_16,color_FFFFFF,t_70#pic_center)
将质心和拟合直线在坐标轴中画出,图片左下角为坐标原点:![在这里插入图片描述](https://img-blog.csdnimg.cn/20210308215707687.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01TRE5fSQ==,size_16,color_FFFFFF,t_70#pic_center)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值