卷积神经网络模型小案例--多分类识别圆形、三角形、四边形

案例模型
在这里插入图片描述

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 22, 22, 32)        896       
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 20, 20, 64)        18496     
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 10, 10, 64)        0         
_________________________________________________________________
flatten (Flatten)            (None, 6400)              0         
_________________________________________________________________
dense (Dense)                (None, 128)               819328    
_________________________________________________________________
dense_1 (Dense)              (None, 3)                 387       
=================================================================
Total params: 839,107
Trainable params: 839,107
Non-trainable params: 0
_________________________________________________________________
None

案例源码

# 调用要使用的包
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

# 指定随机种子
np.random.seed(3)

# 生成数据
train_data = ImageDataGenerator(rescale=1./255,
                                rotation_range=30,
                                width_shift_range=0.1,
                                height_shift_range=0.05,
                                shear_range=0.6,
                                zoom_range=0.4,
                                horizontal_flip=True,
                                vertical_flip=True,
                                fill_mode='nearest')


# 数据增强,增加数据集
# img = load_img('D:\\Users\\86138\\Desktop\\train\\triangle\\triangle018.png')
# x = img_to_array(img)
# x = x.reshape((1,) + x.shape)
# i = 0
# for batch in train_data.flow(x, batch_size=1, save_to_dir='D:\\Users\\86138\\Desktop\\train\\_circle', save_prefix='t015', save_format='png'):
#     i += 1
#     if i >= 100:
#         print('ok')
#         break

train_generator = train_data.flow_from_directory(
    'D:\\Users\\86138\\Desktop\\train',    # train数据存储位置
    target_size=(24, 24),
    batch_size=3,
    class_mode='categorical')

test_data = ImageDataGenerator(rescale=1./255)
test_generator = test_data.flow_from_directory(
    'D:\\Users\\86138\\Desktop\\test',    # test数据存储位置
    target_size=(24, 24),
    batch_size=3,
    class_mode='categorical')

# 搭建模型
model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(24,24,3)))
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(3, activation='softmax'))

# # 生成模型结构
# from keras.models import load_model
# model.save('handwriting.h5')
# print(model.summary())

# 设置模型训练过程
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 训练模型
model.fit_generator(train_generator, steps_per_epoch=1000, epochs=100, validation_data=test_generator, validation_steps=5)
# model.fit(trainX, trainY, batch_size=4, epochs=50)

# 评价模型
print("---Evaluate---")
scores = model.evaluate_generator(test_generator, steps=5)
print("%s: %.2f%%" % (model.metrics_names[0], scores[0]*100))
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# 使用模型
print("---Predict---")
output = model.predict_generator(test_generator, steps=5)
np.set_printoptions(formatter={'float' : lambda x: "{0:0.3f}".format(x)})
print(test_generator.class_indices)
print(output)

训练模型

Found 3000 images belonging to 3 classes.
Found 15 images belonging to 3 classes.
WARNING:tensorflow:From <ipython-input-1-d830ac30df85>:64: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.fit, which supports generators.
Epoch 1/100
1000/1000 [==============================] - 22s 22ms/step - loss: 0.7788 - accuracy: 0.6447 - val_loss: 1.7149 - val_accuracy: 0.6667
Epoch 2/100
1000/1000 [==============================] - 11s 11ms/step - loss: 0.4841 - accuracy: 0.8183 - val_loss: 0.5185 - val_accuracy: 0.7333
Epoch 3/100
1000/1000 [==============================] - 11s 11ms/step - loss: 0.3390 - accuracy: 0.8790 - val_loss: 0.1320 - val_accuracy: 0.9333
Epoch 4/100
1000/1000 [==============================] - 12s 12ms/step - loss: 0.2663 - accuracy: 0.9040 - val_loss: 0.0660 - val_accuracy: 1.0000
...
Epoch 97/100
1000/1000 [==============================] - 11s 11ms/step - loss: 0.0249 - accuracy: 0.9943 - val_loss: 1.5895e-08 - val_accuracy: 1.0000
Epoch 98/100
1000/1000 [==============================] - 12s 12ms/step - loss: 0.0198 - accuracy: 0.9937 - val_loss: 7.9473e-09 - val_accuracy: 1.0000
Epoch 99/100
1000/1000 [==============================] - 11s 11ms/step - loss: 0.0246 - accuracy: 0.9907 - val_loss: 0.0000e+00 - val_accuracy: 1.0000
Epoch 100/100
1000/1000 [==============================] - 11s 11ms/step - loss: 0.0161 - accuracy: 0.9957 - val_loss: 2.1537e-06 - val_accuracy: 1.0000

评价模型

---Evaluate---
WARNING:tensorflow:From <ipython-input-1-d830ac30df85>:69: Model.evaluate_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.evaluate, which supports generators.
loss: 0.00%
accuracy: 100.00%
---Predict---
WARNING:tensorflow:From <ipython-input-1-d830ac30df85>:75: Model.predict_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.predict, which supports generators.
{'circle': 0, 'rectangle': 1, 'triangle': 2}
[[0.000 1.000 0.000]
 [0.000 1.000 0.000]
 [1.000 0.000 0.000]
 [0.000 0.000 1.000]
 [1.000 0.000 0.000]
 [0.000 0.000 1.000]
 [1.000 0.000 0.000]
 [0.000 0.000 1.000]
 [1.000 0.000 0.000]
 [0.000 0.000 1.000]
 [0.000 1.000 0.000]
 [0.000 0.000 1.000]
 [0.000 1.000 0.000]
 [1.000 0.000 0.000]
 [0.000 1.000 0.000]]

训练好的模型以及数据集链接
链接:https://pan.baidu.com/s/1q--Ovb2SIVsoKGxHCdh0MQ 提取码:0lyj 复制这段内容后打开百度网盘手机App,操作更方便哦

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个实现圆形三角形和矩形识别的 OpenCV 代码示例: ```python import cv2 # 定义识别函数 def detect_shape(c): shape = "unknown" peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.04 * peri, True) # 当逼近形状的顶点数为 3 时,判定为三角形 if len(approx) == 3: shape = "triangle" # 当逼近形状的顶点数为 4 时,计算宽高比来判定为矩形 elif len(approx) == 4: (x, y, w, h) = cv2.boundingRect(approx) ar = w / float(h) shape = "rectangle" if ar >= 0.95 and ar <= 1.05 else "square" # 当逼近形状的顶点数为大于 4 时,判定为圆形 else: shape = "circle" return shape # 读取摄像头视频流 cap = cv2.VideoCapture(0) while True: # 读取视频帧 ret, frame = cap.read() # 转换为灰度图像并进行边缘检测 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(blurred, 50, 150) # 寻找轮廓并进行形状识别 cnts, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in cnts: # 忽略过小的轮廓 if cv2.contourArea(c) < 100: continue # 计算轮廓重心并在图像上标注识别结果 M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) shape = detect_shape(c) cv2.drawContours(frame, [c], -1, (0, 255, 0), 2) cv2.putText(frame, shape, center, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) # 显示图像 cv2.imshow("Frame", frame) # 按 'q' 退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放资源 cap.release() cv2.destroyAllWindows() ``` 该代码通过边缘检测和轮廓找到图像中的形状,再根据形状的顶点数和宽高比来判断其为圆形三角形或矩形。在运行代码前,需要确保已安装 OpenCV 库并连接了可用的摄像头设备。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值