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 语句结束时关闭)
目录结构和部分数据如下:
###编了个代码用来测试能否从pos_image.txt中读出图片和图片的路径,也是成功的。
那为什么跑.\opencv_createsamples.exe -vec pos.vec -info pos_image.txt -bg neg_image.txt -w 150 -h 40 -num 40000就是不行呢?