讲解过程视频访问网址:https://www.ixigua.com/6864818246109889036/
esp32-cam的引脚连接表:
直接上代码:
1、esp32-cam(arduino下位机代码)
#include "esp_camera.h"
void setup() {
Serial.begin(115200);//传口速率
Serial.println();//仅输出一个回车和换行符
camera_config_t config1;
//config1.ledc_channel = 4;
config1.pin_d0 = 5;
config1.pin_d1 = 18;
config1.pin_d2 = 19;
config1.pin_d3 = 21;
config1.pin_d4 = 36;
config1.pin_d5 = 39;
config1.pin_d6 = 34;
config1.pin_d7 = 35;
config1.pin_xclk = 0;
config1.pin_pclk = 22;
config1.pin_vsync = 25;
config1.pin_href = 23;
config1.pin_sscb_sda = 26;
config1.pin_sscb_scl = 27;
config1.pin_pwdn = 32;
config1.pin_reset = 15;
config1.xclk_freq_hz = 20000000;
config1.pixel_format = PIXFORMAT_JPEG;
// if PSRAM IC present, init with UXGA resolution and higher JPEG quality
// for larger pre-allocated frame buffer.
if(psramFound()){
config1.frame_size = FRAMESIZE_UXGA;
config1.jpeg_quality = 10;
config1.fb_count = 2;
} else {
config1.frame_size = FRAMESIZE_SVGA;
config1.jpeg_quality = 12;
config1.fb_count = 1;
}
// camera init
esp_err_t err = esp_camera_init(&config1);//摄像头初始化
if (err != ESP_OK) {//摄像头初始化失败,则打印消息并终止程序
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
Serial.printf("camera is runing\n");
sensor_t *s = esp_camera_sensor_get();//获取调整图像接口
s->set_framesize(s, FRAMESIZE_VGA);//更改帧尺寸
//s->set_quality(s, 10);//设置品质10
//acquire a frame获取图像,查看是否改变
camera_fb_t * fb = esp_camera_fb_get();
if (!fb)
{
Serial.print( "Camera capture failed");
}
else
{
Serial.printf("width:%d, height:%d, format:%d, len:%d\r\n", fb->width, fb->height, fb->format, fb->len);//输出width:640, height:480, format:3, len:30805;尺寸小了,但len怎么更长了?
delay(500);
Serial.write(fb->buf, fb->len);//输出图像数据
}
}
void loop() {
}
2、上位机python代码:
#串口图片通讯
#usr/bin/python3
# -*- coding: utf-8 -*-
import serial #python自带串行通讯模块
import matplotlib.pyplot as plt # plt 用于显示图片
import numpy as np
import cv2 #opencv
from time import sleep
ser = serial.Serial('com3', 115200, timeout=0.1) #设置串口名称,波特率,超时时间
def recv(serial):
while True:
data = serial.read(1024)#设置1024缓冲区
if data == '':
continue
else:
break
sleep(0.02)
return data
img = b'' #字节连接,定义全局字节变量以备使用
recev = 0 #接收标志位
while True:
data = recv(ser)
# print(len(data))#图片数据按1024分段接收
# print(type(data))#output:<class 'bytes'>
if data:
try:
print(data.decode())
except:
if (b'\xff\xd8' in data) or (recev):#jpg图片开始字节为b'\xff\xd8',若存在则开始接受数据,接下来用标志位保持接收
recev = 1 #接收标志位置1
img += data #图片接收后分段连接
print('开始接收图片:',len(img))#图片数据按1024分段接收
#sleep(0.02)#不加延时下面的判断会出错
if b'\xff\xd9' in data: #jpg图片开始字节为b'\xff\xd9,若存在则停止接受数据
print('接收图片完成:',len(img))#图片数据按1024分段接收
nparr = np.frombuffer(img, np.uint8)#图片字节数据转换np.uint8
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) #利用opencv转换成图片格式
print(np.shape(img_np))
plt.imshow(img_np[:,:,::-1]) # 显示图片,opencv的bgr转换用[:,:,::-1]操作即可
#plt.axis('off') # 不显示坐标轴
plt.show()
img = b'' #完成图片显示,清空图片缓冲区内存
recev = 0 #接收标志位置0
3、使用方法:
烧写esp32-cam代码完成后,运行上位机python代码,按esp32-cam板上的重启重启键即可看到输出。