opencv 摄像头 指定大小 数量 的图片

毕设需要做图片识别,不想用已经有的数据集,所以写了一个基于opencv通过笔记本摄像头采集指定数量的py文件,下面的常量可以根据需要更改,别的不说直接上代码 中间注释掉的部分是对图像做的一些处理,如果用不上可以删除,备注写的比较简单,不好意思
# -*- coding:utf-8-*-
import cv2
import os
import time
import numpy as np
width = 200
height = 200          # 图片大小
numofsamples = 300   # 每个手势录制的样本数
counter = 0         # 计数器,记录已经录制多少图片了
path = ".\\data\\"

cap = cv2.VideoCapture(0) # 创建一个视频捕捉对象 # 0为(笔记本)内置摄像头
gesturename = (input("enter the gesture folder name: "))
while(True): # 读帧
    ret, frame = cap.read()
    res = cv2.resize(frame,(200,200),interpolation=cv2.INTER_CUBIC)
    print(res.shape)
    # #转换为灰度图
    gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY)
    #
    # gradX = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
    # gradY = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)
    #
    # gradient = cv2.subtract(gradX, gradY)
    # gradient = cv2.convertScaleAbs(gradient)
    # # 去除图像上的噪声
    # blurred = cv2.blur(gradient, (9, 9))
    # (_, thresh) = cv2.threshold(blurred, 90, 255, cv2.THRESH_BINARY)
    # # 填充空白区域
    # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,25))
    # closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    # #执行4次形态学腐蚀
    # closed = cv2.erode(closed, None, iterations=4)
    # closed = cv2.dilate(closed, None, iterations=4)
    # # 找轮廓
    # (image,cnts, _,) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # c = sorted(cnts, key=cv2.contourArea,reverse=True)[0]
    #
    # rect = cv2.minAreaRect(c)
    # box = np.int0(cv2.boxPoints(rect))
    # cv2.drawContours(res, [box], -1, (0, 255, 0), 3)
    #裁剪
    # Xs = [i[0] for i in box]
    # Ys = [i[1] for i in box]
    # x1 = min(Xs)
    # x2 = max(Xs)
    # y1 = min(Ys)
    # y2 = max(Ys)
    # height = y2 - y1
    # width = x2 -x1
    # cropImg = image[y1:y1+height, x1: x1+width]
    if not os.path.exists(path +'\\'+gesturename):
        os.makedirs(path +'\\'+gesturename)
    if counter<numofsamples:
        counter += 1
        name = gesturename + str(counter)  # 给录制的手势命名
        print("Saving img: ", name)
        cv2.imshow('picture', res)
        cv2.imwrite(path +'\\\\'+gesturename+ '\\\\'+name + '.png', res)  # 写入文件

        time.sleep(0.05)
       # cv2.imwrite('1.jpg', gray)
    else:
        print('已经获取'+str(numofsamples)+'张图片')
        break

    #PATH1 = path +'\\\\'+gesturename

cap.release()
cv2.destroyAllWindows()

  

posted @ 2018-04-14 19:48  可以用标点做名字吗  Views(994)  Comments(0Edit  收藏  举报