涉及到了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()
处理结果图
求质心的直线拟合:
将质心和拟合直线在坐标轴中画出,图片左下角为坐标原点: