SLR_ZY 2024-02-29 12:20 采纳率: 0%
浏览 13

训练级联分类器时报错

OpenCV

在训练级联分类器的时候遇到了问题:

.\opencv_createsamples.exe -vec pos.vec -info pos_image.txt -bg neg_image.txt -w 150 -h 40 -num 40000
Info file name: pos_image.txt
Img file name: (NULL)
Vec file name: pos.vec
BG  file name: neg_image.txt
Num: 40000
BG color: 0
BG threshold: 80
Invert: FALSE
Max intensity deviation: 40
Max x angle: 1.1
Max y angle: 1.1
Max z angle: 0.5
Show samples: FALSE
Width: 150
Height: 40
Max Scale: -1
RNG Seed: 12345
Create training samples from images collection...
Unable to open image: 0
Unable to open image: 22
pos_image.txt(3) : parse errorDone. Created 1 samples

程序代码如下:

import cv2
import hashlib
import os
import pandas as pd
import numpy as np

# 创建输出目录
if not os.path.exists("output"):
    os.makedirs("output")

h, w = 40, 150
data_path = r"E:\OpenCV\CCPD2019\ccpd_base"

# 获取所有文件名
filenames = os.listdir(data_path)

# 打开文本文件
with open("pos_image.txt", "w", encoding="utf-8") as fp, \
     open("neg_image.txt", "w", encoding="utf-8") as fn:

    df = pd.DataFrame(columns=('pic_name', '0', '1', '2', '3', '4', '5', '6'))

    # 处理正样本图片
    for img_idx, img_name in enumerate(filenames[0:10000]):
        # 将数据集路径与当前图片文件名拼接成完整图片文件路径
        image_path = os.path.join(data_path, img_name)
        if not os.path.isfile(image_path):
            print(f"File does not exist: {image_path}")
            continue
        # 使用OpenCV库的imread函数读取该图片
        # imread方法将图片从指定路径加载到内存中,并以numpy数组的形式返回,该数组通常包含图像的BGR通道值
        image = cv2.imread(image_path)
        if image is None:
            print(f"Error occurred while reading image from {image_path}")
            continue

        # 分割车牌信息
        img_info = img_name.rsplit('/', 1)[-1].rsplit('.', 1)[0].split('-')
        plate_chars = img_info[4].split("_")

        # 存储到DataFrame中
        new_line = [f'pic{img_idx + 1:06d}'] + plate_chars
        df.loc[len(df)] = new_line

        # 裁剪并调整车牌大小
        left_up, right_down = [[int(eel) for eel in el.split('&')] for el in img_info[2].split('_')]
        crop_img = image[left_up[1]:right_down[1], left_up[0]:right_down[0]]
        resized_img = cv2.resize(crop_img, (w, h))

        # 对正样本图片进行灰度化处理
        resized_gray_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)

        pos_dir = os.path.join("output", "pos")
        if not os.path.exists(pos_dir):
            os.makedirs(pos_dir)

        # 然后保存灰度化的车牌图片
        try:
            output_path = os.path.join("output/pos", f"pic{img_idx + 1:06d}.jpg")
            cv2.imwrite(output_path, resized_gray_img, [cv2.IMWRITE_JPEG_QUALITY, 95])  # 使用灰度图像写入,并设定JPEG质量
        except Exception as e:
            print(f"Error occurred while writing grayscale image to {output_path}: {e}")

        # 写入txt文件
        relative_output_path = os.path.join("output", "pos", os.path.basename(output_path))
        fp.write(f'{relative_output_path} 1 0 0 {w} {h} {" ".join(plate_chars)}\n')

    # 保存DataFrame为csv文件
    df.to_csv('./pos.csv')

    # 处理负样本图片(假设没有包含车牌坐标信息,随机裁剪)
    for neg_img_idx, img_name in enumerate(filenames[10000:30000]):
        image_path = os.path.join(data_path, img_name)
        image = cv2.imread(image_path)

        # 随机裁剪不含车牌区域
        random_crop = image[0:40, 0:150]
        neg_output_path = os.path.join("output/neg", f"pic{neg_img_idx + 10001:06d}.jpg")
        # 同样地,如果需要对负样本也进行灰度化处理
        random_gray_crop = cv2.cvtColor(random_crop, cv2.COLOR_BGR2GRAY)

        neg_dir = os.path.join("output", "neg")
        if not os.path.exists(neg_dir):
            os.makedirs(neg_dir)

        cv2.imwrite(neg_output_path, random_gray_crop, [cv2.IMWRITE_JPEG_QUALITY, 95])

        # 写入txt文件
        relative_neg_output_path = os.path.join("output", "neg", os.path.basename(neg_output_path))
        fn.write(f'{relative_neg_output_path}\n')

# 自动关闭文件(文本文件会自动在 with 语句结束时关闭)

目录结构和部分数据如下:

img

###编了个代码用来测试能否从pos_image.txt中读出图片和图片的路径,也是成功的。
那为什么跑.\opencv_createsamples.exe -vec pos.vec -info pos_image.txt -bg neg_image.txt -w 150 -h 40 -num 40000就是不行呢?

  • 写回答

3条回答 默认 最新

  • 关注

    SLR_ZY 中午好🌞🌞🌞
    本答案参考通义千问

    错误原因: 在训练级联分类器时,OpenCV遇到了一个错误,提示无法打开某个图像文件(D:\PyCharm2023\Projects\License\.venv\pic000001.jpg)。这个错误是由于文件路径不正确或者文件不存在导致的。

    解决方案:

    1. 检查文件路径和名称: 确保提供的图像文件 pic000001.jpg 的路径和名称是正确的,并且文件确实存在于指定的目录下。请检查 data_path 变量指向的路径是否正确。

    2. 逐个处理文件: 你可以尝试遍历文件列表,逐个尝试读取文件,以便定位出问题的文件。例如,在代码中添加一个循环来检查每个图像文件:

    for img_idx, img_name in enumerate(filenames):
        image_path = os.path.join(data_path, img_name)
        if not os.path.isfile(image_path):  # 检查文件是否存在
            print(f"Image file {image_path} does not exist. Skipping...")
            continue
        try:
            image = cv2.imread(image_path)
            # ...其他处理
        except Exception as e:
            print(f"Error reading image {image_path}: {e}")
    
    1. 修复或替换问题文件: 如果找到问题是由于文件损坏或丢失,需要修复或替换有问题的文件。确保所有用于训练的数据都可用。

    2. 检查文件编码: 确保文本文件(如pos_image.txtneg_image.txt)的编码与你的程序使用的编码一致。如果需要,可以使用open函数的encoding参数指定正确的编码。

    3. 清理或重新创建输出目录: 如果文件权限问题导致无法访问,试着清理或重新创建 output 目录,然后再次运行程序。

    4. 确保负样本图片的处理: 对于负样本图片,确保它们已经按照预期被正确裁剪和存储。检查 random_cropneg_output_path 的处理逻辑。

    更新代码示例:

    # ...其他代码不变
    
    # 更新处理正样本图片的部分
    for img_idx, img_name in enumerate(filenames):
        # ...其他处理
        if not os.path.isfile(image_path):
            print(f"Skipping image {img_name} due to missing file.")
            continue
        try:
            # ...裁剪、调整大小、保存灰度图片等步骤
        except Exception as e:
            print(f"Error processing image {img_name}: {e}")
    
    # ...其他代码
    

    请根据上述建议检查和修复你的代码,以解决训练级联分类器时遇到的问题。

    评论

报告相同问题?

问题事件

  • 修改了问题 3月1日
  • 修改了问题 3月1日
  • 修改了问题 2月29日
  • 创建了问题 2月29日

悬赏问题

  • ¥20 校园二手交易小程序搭建
  • ¥15 请问在ubuntu用conda创建环境报错怎么能解决
  • ¥15 STM32CubeMX/proteus按键控制指示灯颜色切换
  • ¥20 python,计算区位熵和扩张指数
  • ¥15 Python环境配置
  • ¥15 大四学生的困惑,有偿提问!
  • ¥15 解决页面无法编入索引:被“noindex”标签排除的问题?
  • ¥15 arduino测量电阻
  • ¥15 快手uid转快手号谁能解决 需要开发
  • ¥15 iis部署Django时css不生效,来个真人,ai不好使