|
楼主 |
发表于 2022-5-12 18:36:22
|
显示全部楼层
# coding: utf-8
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.vq import *
from pylab import *
from PIL import Image
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
frame = cv2.flip(
frame,
1 #1:水平镜面;-1:垂直
)
#读取原始图像
img = frame
#图像二维像素转换为一维
data = img.reshape((-1,3))
data = np.float32(data)
#定义中心 (type,max_iter,epsilon)
criteria = (cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
#设置标签
flags = cv2.KMEANS_RANDOM_CENTERS
#K-Means聚类 聚集成2类
compactness, labels, centers = cv2.kmeans(data, 3, None, criteria, 10, flags)
#图像转换回uint8二维类型
centers = np.uint8(centers)
res = centers[labels.flatten()]
dst = res.reshape((img.shape))
#图像转换为RGB显示
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
dst = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)
#用来正常显示中文标签
plt.rcParams['font.sans-serif']=['SimHei']
cv2.imshow("dst", dst)
if cv2.waitKey(1) &0xFF == ord('q'):
break
#当一切完成,释放捕获
cap.release()
cv2.destroyALLWindows() |
|