要求:应用轮廓相关知识,对图片进行处理,分别用矩形、圆形识别饮料,输出各自的中心点,矩形的长宽、圆形的半径,得到四个极点。
# 获取图像的阈值,创建掩膜
low = np.array([0, 153, 28])
up = np.array([80, 232, 197])
mask = cv2.inRange(hsv, low, up)
img1 = cv2.bitwise_and(img, img, mask=mask)
上述代码用已创建的HSV格式创建掩膜,获取到需要图片区域,用于后面二值化,获取图像轮廓
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, hie = cv2.findContours(
thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
上述代码将图片转为灰度图片,然后进行自适应化二值化,把图片转化为黑白模式,用于寻找图片轮廓
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]
cnt = contours[0]
上述代码用于在多个矩形轮廓中选取最适合图片的轮廓,即轮廓中最大的那个
x, y, w, h = cv2.boundingRect(cnt)
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
print("矩形参数为:")
print(w)
上述代码用于绘制最适应轮廓的矩形,并输出矩形的信息
# 绘制最小外接圆
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 255, 0), 2)
print("圆心为:")
print((x, y))
上述代码用于绘制最小的外接圆并输出圆的信息
# 获取四个极点
left = tuple(cnt[cnt[:, :, 0].argmin()][0])
right = tuple(cnt[cnt[:, :, 0].argmax()][0])
top = tuple(cnt[cnt[:, :, 1].argmin()][0])
bottom = tuple(cnt[cnt[:, :, 1].argmax()][0])
创建掩膜,与运算结果图片
最终结果截图:
完整代码:
import cv2
import numpy as np
# 将图片转化为HSV格式,此格式为三通道
img = cv2.imread('juice.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 获取图像的阈值,创建掩膜
low = np.array([0, 153, 28])
up = np.array([80, 232, 197])
mask = cv2.inRange(hsv, low, up)
img1 = cv2.bitwise_and(img, img, mask=mask)
cv2.namedWindow('old', cv2.WINDOW_NORMAL)
cv2.imshow('old', img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 将图形转为灰度,用于后面自适应二值化
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, hie = cv2.findContours(
thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 寻找最大面积的矩形,来进行操作
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]
cnt = contours[0]
print('单个矩形参数:')
M = cv2.moments(cnt)
print(M)
# 绘制矩形
x, y, w, h = cv2.boundingRect(cnt)
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
print("矩形参数为:")
print(w)
# 绘制最小外接圆
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 255, 0), 2)
print("圆心为:")
print((x, y))
cv2.namedWindow('new', cv2.WINDOW_NORMAL)
cv2.imshow('new', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 获取四个极点
left = tuple(cnt[cnt[:, :, 0].argmin()][0])
right = tuple(cnt[cnt[:, :, 0].argmax()][0])
top = tuple(cnt[cnt[:, :, 1].argmin()][0])
bottom = tuple(cnt[cnt[:, :, 1].argmax()][0])
print('极点参数为:')
print(left)
print(right)
print(top)
print(bottom)