python opencv通过按键采集图片源码


Posted in Python onMay 20, 2021

一、python版本

写了个python opencv的小demo,可以通过键盘按下字母s进行采集图像。

功能说明

“N” 新建文件夹 data/ 用来存储图像
“S” 开始采集图像,将采集到的图像放到 data/ 路径下
“Q” 退出窗口

python opencv源码

'''

“N”  新建文件夹 data/  用来存储图像
"S"   开始采集图像,将采集到的图像放到 data/ 路径下
“Q”   退出窗口
'''

import numpy as np  # 数据处理的库 Numpy
import cv2          # 图像处理的库 OpenCv
import os           # 读写文件
import shutil       # 读写文件
from PIL import Image, ImageDraw, ImageFont


# # OpenCv 调用摄像头 / Use camera
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH,1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)

'''
#功能函数,只是用来往图片中显示汉字
#示例 img = cv2ImgAddText(cv2.imread('img1.jpg'), "大家好,我是片天边的云彩", 10, 65, (0, 0, 139), 20)
参数说明:
img:OpenCV图片格式的图片
text:要写入的汉字
left:字符坐标x值
top:字符坐标y值
textColor:字体颜色
:textSize:字体大小
'''
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

# 存储图像的文件夹 
current_dir = ""
# 保存  图像 的路径 
path_photos_from_camera = "data/"

press_n_flag = 0
cnt_ss=0



while cap.isOpened():
    flag, img_rd = cap.read()
    #print(img_rd.shape)

    kk = cv2.waitKey(2)
    # 待会要写的字体 / Font to write
    font = cv2.FONT_ITALIC

    # 4. 按下 'n' 新建存储人脸的文件夹 / press 'n' to create the folders for saving faces
    if kk == ord('N') or kk == ord('n'):
        current_dir = path_photos_from_camera
        #os.makedirs(current_dir)
        if os.path.isdir(current_dir):
            pass
        else:
            os.mkdir(current_dir)
        print('\n')
        print("新建的保存图像的文件夹 / Create folders: ", current_dir)

        press_n_flag = 1        # 已经按下 'n' / have pressed 'n'


    # 5. 按下 's' 保存摄像头中的图像到本地 / Press 's' to save image into local images
    if kk == ord('S') or kk == ord('s'):
        # 检查有没有先按'n'新建文件夹 / check if you have pressed 'n'
        if press_n_flag:
            cnt_ss += 1
            cv2.imwrite(current_dir + "/img_" + str(cnt_ss) + ".jpg", img_rd)
            print("写入本地 / Save into:", str(current_dir) + "/img_face_" + str(cnt_ss) + ".jpg")
        else:
            print("请在按 'S' 之前先按 'N' 来建文件夹 / Please press 'N' before 'S'")


    # 添加说明 / Add some statements
    #cv2.putText(img_rd, "Face Register", (20, 40), font, 1, (0, 255, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "图片采集系统", 160, 25, (0, 255,0), 30)
    #cv2.putText(img_rd, "N: Create face folder", (20, 350), font, 0.8, (0, 255, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "N: 创建保存图像文件夹", 20, 350, (0, 255, 0), 20)
    #cv2.putText(img_rd, "S: Save current face", (20, 400), font, 0.8, (0, 255, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "S: 保存当前图片", 20, 400, (0, 255, 0), 20)
    #cv2.putText(img_rd, "Q: Quit", (20, 450), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
    img_rd = cv2ImgAddText(img_rd, "Q: 退出", 20, 450, (0, 255, 0), 20)

    # 6. 按下 'Q' 键退出 / Press 'q' to exit
    if kk == ord('Q') or kk == ord('q'):
        break
    # 如果需要摄像头窗口大小可调 / Uncomment this line if you want the camera window is resizeable
    cv2.namedWindow("camera", 0)
    cv2.imshow("camera", img_rd)

# 释放摄像头 / Release camera and destroy all windows
cap.release()
cv2.destroyAllWindows()

效果图

python opencv通过按键采集图片源码

安装相关库

windows安装

pip install pillow

tx2/linux/…

sudo apt-get install python3-pillow

二、c语言版本

 c语言源码

/*****************************************************
2021.5.18:按键采集图像
******************************************************/
#include "opencv2/core/core.hpp"    
#include "opencv2/imgproc/imgproc.hpp"    
#include "opencv2/calib3d/calib3d.hpp"    
#include "opencv2/highgui/highgui.hpp"    
#include <iostream>    
#include <fstream>    

using namespace cv;
using namespace std;

#define SRC_WIDTH  1920
#define SRC_HEIGHT 1080

int main()
{
	//测试视频
	VideoCapture capture;
	capture.open(1);
	//capture.open("v4l2src device=/dev/video4 ! video/x-raw,width=1920,height=1020,framerate=30/1 ! videoconvert ! appsink");
	if (!capture.isOpened())
	{
		printf("文件打开失败");
	}
	capture.set(CAP_PROP_FRAME_WIDTH, SRC_WIDTH);        //设置宽度
	capture.set(CAP_PROP_FRAME_HEIGHT, SRC_HEIGHT);  //设置长度
	Mat frame;
	int n = 0;
	char* cstr = new char[120];
	while (true)
	{
		
		capture >> frame;
		if (frame.data == NULL)
		{
			printf("Image is empty\n");
			//writer.write(frame);
			break;
			//continue;
		}
		char kk=waitKey(2);
		if (kk == 'S' || kk == 's')
		{

			sprintf(cstr, "%s%d%s", "caliberation/", n++, ".jpg");
			imwrite(cstr, frame);
			printf("保存了图片\n");

		}

		
		namedWindow("111", 0);//参数为零,则可以自由拖动
		imshow("111", frame);
		waitKey(2);
	}

	return 0;

}

效果图

python opencv通过按键采集图片源码

到此这篇关于opencv通过按键采集图片源码的文章就介绍到这了,更多相关opencv按键采集图片内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python中使用gzip模块压缩文件的简单教程
Apr 08 Python
Python标准库defaultdict模块使用示例
Apr 28 Python
Django小白教程之Django用户注册与登录
Apr 22 Python
python实现下载文件的三种方法
Feb 09 Python
django表单实现下拉框的示例讲解
May 29 Python
Python求一批字符串的最长公共前缀算法示例
Mar 02 Python
用Python实现BP神经网络(附代码)
Jul 10 Python
python实现复制大量文件功能
Aug 31 Python
python之pymysql模块简单应用示例代码
Dec 16 Python
在Python中利用pickle保存变量的实例
Dec 30 Python
详解anaconda离线安装pytorchGPU版
Sep 08 Python
深入探讨opencv图像矫正算法实战
May 21 Python
python 如何执行控制台命令与操作剪切板
教你怎么用Python生成九宫格照片
用 Python 元类的特性实现 ORM 框架
May 19 #Python
浅谈Python 中的复数问题
May 19 #Python
Python机器学习之基础概述
Python机器学习之PCA降维算法详解
Python 批量下载阴阳师网站壁纸
May 19 #Python
You might like
用PHP4访问Oracle815
2006/10/09 PHP
phpMyAdmin 安装及问题总结
2009/05/28 PHP
php采集文章中的图片获取替换到本地(实现代码)
2013/07/08 PHP
PHP+jQuery+Ajax实现用户登录与退出
2015/04/27 PHP
PHP实现基于图的深度优先遍历输出1,2,3...n的全排列功能
2017/11/10 PHP
简单实用的PHP文本缓存类实例
2019/03/22 PHP
在js中使用&quot;with&quot;语句中跨frame的变量引用问题
2007/03/08 Javascript
下拉列表select 由左边框移动到右边示例
2013/12/04 Javascript
js换图片效果可进行定时操作
2014/06/09 Javascript
javascript进行四舍五入方法汇总
2014/12/16 Javascript
JavaScript中的依赖注入详解
2015/03/18 Javascript
jQuery Dialog 取消右上角删除按钮事件
2016/09/07 Javascript
jQuery操作复选框(CheckBox)的取值赋值实现代码
2017/01/10 Javascript
Angular.js中angular-ui-router的简单实践
2017/07/18 Javascript
浅谈JavaScript的innerWidth与innerHeight
2017/10/12 Javascript
two.js之实现动画效果示例
2017/11/06 Javascript
JavaScript实现元素滚动条到达一定位置循环追加内容
2017/12/28 Javascript
webstorm和.vue中es6语法报错的解决方法
2018/05/08 Javascript
vue中的v-if和v-show的区别详解
2019/09/01 Javascript
layui输入框只允许输入中文且判断长度的例子
2019/09/18 Javascript
原生JavaScript之es6中Class的用法分析
2020/02/23 Javascript
用javascript实现倒计时效果
2021/02/09 Javascript
python合并同类型excel表格的方法
2018/04/01 Python
Anaconda下安装mysql-python的包实例
2018/06/11 Python
Python+OpenCV采集本地摄像头的视频
2019/04/25 Python
PyTorch中torch.tensor与torch.Tensor的区别详解
2020/05/18 Python
Python3如何使用range函数替代xrange函数
2020/10/05 Python
基于 HTML5 的 WebGL 3D 版俄罗斯方块的示例代码
2018/05/28 HTML / CSS
摩托车和ATV零件、配件和服装的首选在线零售商:MotoSport
2017/12/22 全球购物
Nordgreen手表德国官方网站:丹麦极简主义手表
2019/10/31 全球购物
《学会待客》教学反思
2014/02/22 职场文书
廉洁使者实施方案
2014/03/29 职场文书
结对共建协议书
2014/08/20 职场文书
商铺门面租房协议书
2014/10/21 职场文书
单方离婚协议书范本2014
2014/10/28 职场文书
2019年描写人生经典诗句大全
2019/07/08 职场文书