获取图片
import cv2
import numpy as np
image = cv2.imread("2.png")
from PIL import Image
img_cv_bgr = Image.fromarray(image)
img_cv_bgr
转化成灰度图片
image2 = cv2.medianBlur(image, 1)
gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
img_cv_bgr = Image.fromarray(gray)
img_cv_bgr
边界提取
边界核定义
kernel = np.array([
[1, 2.2, 1],
[0, 0, 0],
[-1, -2.8, -1]
])
rgb = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)
resulting_image = cv2.filter2D(rgb, -1, kernel)
img_cv_bgr = Image.fromarray(resulting_image)
img_cv_bgr
二值化
gray = cv2.cvtColor(resulting_image, cv2.COLOR_RGB2GRAY)
#显示值大于100的区域
ret, th = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
img_cv_bgr = Image.fromarray(th)
img_cv_bgr
膨胀操作
膨胀大小为2x2
kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
th_close = cv2.dilate(th, kernel2, iterations=2)
img_cv_bgr = Image.fromarray(th_close)
img_cv_bgr
腐蚀操作
腐蚀操作,减少连通区域
kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
th_close = cv2.erode(th, kernel2, iterations=1)
img_cv_bgr = Image.fromarray(th_close)
img_cv_bgr
连通域分析
该函数输入为一个二值化图像,输出为一个长为4的tuple:
- 第一个是连通区域的个数,
- 第二个是一整张图的label,
- 第三个是(x, y, width, height, area),即每个区域的每个区域的左上角坐标,宽和高,面积
- 第四个是每个连通区域的中心点
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(th_close, connectivity=4)
石子数量
num_labels
66