Камера Esp32 с чатом gpt api Vision дает сбой или возникают проблемы с подключениемC++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Anonymous
 Камера Esp32 с чатом gpt api Vision дает сбой или возникают проблемы с подключением

Сообщение Anonymous »

Я создаю проект, используя API чата GPT Vision с esp32cam. Работает для первого цикла (первое изображение оно делает и отправляет в gpt чата), но esp32 дает сбой (Ошибка медитации гуру: ядро ​​1 запаниковало (LoadProhibited). Исключение не было обработано.) или получает «ошибку соединения» с gpt чата, когда я пытаюсь сделать еще один снимок. Нужна помощь. Вот мой код: (я использовал gpt чата, чтобы попытаться исправить код, но не помогло)

Код: Выделить всё

#include "esp_camera.h"
#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include "WiFi.h"
#include 
#include 
#include "Base64.h"
#include "ChatGPT.hpp"
#include "credentials.h" // WiFi credentials and OpenAI API key

#define CAMERA_MODEL_XIAO_ESP32S3 // Has PSRAM

#include "camera_pins.h"

int imageCount = 1;                // File Counter
bool camera_sign = false;          // Check camera status
bool sd_sign = false;              // Check sd status
int button = 0;
const int buttonPin = 3;           // Pin where the button is connected

WiFiClientSecure client;  // WiFiClientSecure for HTTPS connection
ChatGPT chatGPT_Client(&client, "v1", openai_api_key, 90000);  // Use WiFiClientSecure for HTTPS

void connectToWiFi() {
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi...");

// Wait until the device is connected to WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
}

// Function to delete all files in the root directory
void deleteAllFiles(fs::FS &fs) {
File root = fs.open("/");
File file = root.openNextFile();
while (file) {
fs.remove(file.name());  // Delete each file
file = root.openNextFile();
}
Serial.println("All files deleted from SD card.");
}

// Function to create necessary folders
void createFolders(fs::FS &fs) {
if (!fs.exists("/pictures")) {
fs.mkdir("/pictures");
Serial.println("Created folder: /pictures");
}
if (!fs.exists("/encoded")) {
fs.mkdir("/encoded");
Serial.println("Created folder: /encoded");
}
}

// SD card write file
void writeFile(fs::FS &fs, const char * path, uint8_t * data, size_t len){
Serial.printf("Writing file: %s\r\n", path);

File file = fs.open(path, FILE_WRITE);
if(!file){
Serial.println("Failed to open file for writing");
return;
}
if(file.write(data, len) == len){
Serial.println("File written");
} else {
Serial.println("Write failed");
}
file.close();
}

// Save pictures to SD card and send to GPT-4o Mini Vision API
void photo_save_and_analyze(const char * fileName) {
// Take a photo
camera_fb_t *fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Failed to get camera frame buffer");
delay(1000);  // Delay to prevent rapid retries
return;
}

// Encode image to Base64
String encodedImage = base64::encode(fb->buf, fb->len);

// Save photo to file in the /pictures directory
writeFile(SD, fileName, fb->buf, fb->len);

// Release image buffer
esp_camera_fb_return(fb);

if (!SD.exists(fileName)) {
Serial.println("Failed to save photo to SD card");
return;
}

Serial.println("Photo saved to file");

// Prepend the base64 prefix to the encoded image
String base64Image = "data:image/jpeg;base64," + encodedImage;
encodedImage = "";  // Free memory by clearing the string

// Now send the Base64-encoded image to the GPT-4o Vision API
String result;
Serial.println("\n\n[ChatGPT] - Asking a Vision Question");

client.setInsecure();  // Skip certificate verification (use with caution)

if (!client.connected()) {
Serial.println("Reconnecting WiFi client...");
client.stop();
connectToWiFi();   // Re-establish WiFi connection
}

if (chatGPT_Client.vision_question("gpt-4o-mini", "user", "text", "What’s in this image?", "image_url", base64Image.c_str(), "auto", 5000, true, result)) {
Serial.print("[ChatGPT] Response: ");
Serial.println(result);
} else {
Serial.print("[ChatGPT] Error: ");
Serial.println(result);
}

base64Image = "";  // Ensure allocated memory is freed after encoding
}

void setup() {
Serial.begin(115200);
while(!Serial); // When the serial monitor is turned on, the program starts to execute

camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.frame_size = FRAMESIZE_UXGA;
config.pixel_format = PIXFORMAT_JPEG; // for streaming
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
config.fb_location = CAMERA_FB_IN_PSRAM;
config.jpeg_quality = 12;
config.fb_count = 1;

// if PSRAM IC present, init with UXGA resolution and higher JPEG quality
if(config.pixel_format == PIXFORMAT_JPEG){
if(psramFound()){
config.jpeg_quality = 10;
config.fb_count = 2;
config.grab_mode = CAMERA_GRAB_LATEST;
} else {
// Limit the frame size when PSRAM is not available
config.frame_size = FRAMESIZE_SVGA;
config.fb_location = CAMERA_FB_IN_DRAM;
}
} else {
// Best option for face detection/recognition
config.frame_size = FRAMESIZE_240X240;
#if CONFIG_IDF_TARGET_ESP32S3
config.fb_count = 2;
#endif
}

// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}

camera_sign = true; // Camera initialization check passes

// Initialize SD card
if(!SD.begin(21)){
Serial.println("Card Mount Failed");
return;
}
uint8_t cardType = SD.cardType();

// Determine if the type of SD card is available
if(cardType == CARD_NONE){
Serial.println("No SD card attached");
return;
}

Serial.print("SD Card Type: ");
if(cardType == CARD_MMC){
Serial.println("MMC");
} else if(cardType == CARD_SD){
Serial.println("SDSC");
} else if(cardType == CARD_SDHC){
Serial.println("SDHC");
} else {
Serial.println("UNKNOWN");
}

sd_sign = true; // SD initialization check passes

// Delete all files and create folders
deleteAllFiles(SD);      // Delete all files on boot
createFolders(SD);       // Create "pictures" and "encoded" folders

Serial.println("Photos will begin in one minute, please be ready.");

// Connect to WiFi
connectToWiFi();
}

void loop() {
if (touchRead(4) = 25000 && button == 0) {
delay(500);
if (touchRead(4) >= 25000 && button == 0) {
char filename[64];
sprintf(filename, "/pictures/image%d.jpg", imageCount);  // Save to the pictures folder only
photo_save_and_analyze(filename);
Serial.printf("Saved and analyzed picture: %s\r\n", filename);
delay(5000);
imageCount++;
button = 1;

}
}
delay(50);
}
Я использовал чат GPT, чтобы исправить это, я новичок, у меня мало опыта. Код создан путем копирования примеров кодов из библиотек GitHub или тех, которые я нашел в Google, но я понимаю большую часть того, как он работает. Я пробовал повторно подключать его Wi-Fi после каждого сделанного изображения, очищая переменные base64 и добавляя задержки, чтобы дать gpt время отреагировать. Мне ничего не помогло.

Подробнее здесь: https://stackoverflow.com/questions/791 ... connecting
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C++»