请把上面的这段代码封装为一个函数
时间: 2024-02-13 15:02:37 浏览: 30
好的,以下是封装好的函数:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
def liquid_concentration_prediction(image_path):
# 读入图片
img = cv2.imread(image_path)
# 获取图片长宽
height, width = img.shape[:2]
# 计算每个圆的半径
width = max(width, height)
height = min(width, height)
a = int(width / 12) / 2
b = int(height / 8) / 2
c = int(a)
d = int(b)
r = min(c, d)
# 计算圆心坐标
centers = []
for j in range(8):
for i in range(12):
cx = 2 * r * j + r
cy = 2 * r * i + r
centers.append((cx, cy))
# 提取灰度值
gray_values = []
for i in range(96):
x, y = centers[i][0], centers[i][1]
mask = np.zeros_like(img)
cv2.circle(mask, (x, y), r, (255, 255, 255), -1)
masked_img = cv2.bitwise_and(img, mask)
gray_img = cv2.cvtColor(masked_img, cv2.COLOR_RGB2GRAY)
gray_value = np.mean(gray_img)
gray_values.append(gray_value)
# 拟合数据
x_values = gray_values[:16] # 16个用于训练的灰度值
x_prediction_values = gray_values[16:] # 80个用于预测的灰度值
y_values = [0.98, 0.93, 0.86, 0.79, 0.71, 0.64, 0.57, 0.50, 0.43, 0.36, 0.29, 0.21, 0.14, 0.07, 0.05, 0.01] # 16个液体浓度值
# 使用numpy的polyfit函数进行线性拟合
fit = np.polyfit(x_values, y_values, 1)
# 使用拟合系数构建线性函数
lin_func = np.poly1d(fit)
# 生成新的80个数据的x值
new_x = x_prediction_values
# 预测新的80个数据的y值
new_y = lin_func(new_x)
# 输出预测结果
result = list(new_y)
row3 = result[:8]
row4 = result[8:16]
row5 = result[16:24]
row6 = result[24:32]
row7 = result[32:40]
row8 = result[40:48]
row9 = result[48:56]
row10 = result[56:64]
row11 = result[64:72]
row12 = result[72:80]
print("第三列:", row3)
print("第四列:", row4)
print("第五列:", row5)
print("第六列:", row6)
print("第七列:", row7)
print("第八列:", row8)
print("第九列:", row9)
print("第十列:", row10)
print("第十一列:", row11)
print("第十二列:", row12)
```
这个函数接收一个图片路径作为参数,然后输出预测结果。你可以通过调用该函数来进行液体浓度的预测。