#机器学习(数据+特征+分类器)4 预测检验
#视频与图片的分解合成,hog特征原理 Harr特征原理 SVM分类器的原理 Adaboost分类器原理 HOG+SVM小狮子检测#
#harr 模板 Adaboost 三级(强分类器 弱分类器 node)
#01 视频分解图片
#1 load 2 info 3 parse 4 imshow ,inmwrite
#(准备样本来做的)
import cv2
cap=cv2.VideoCapture(r'C:\Users\Administrator\Desktop\1.mp4')
isopened=cap.isOpened #判断是否打开打开才可以执行后续操作
print(isopened)
fps=cap.get(cv2.CAP_PROP_FPS)#帧率
width=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))#w
height=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))#h
print(fps,width,height)
i=0 #(记录当前保存了多少张)
while(isopened):
if i==10:
break;
else:
i=i+1
(flag,frame)=cap.read()#读取每一张 flag:表明是否读取成功 frame:图片的内容
filename='image'+str(i)+'.jpg'
print(filename)
if flag==True:
cv2.imwrite(filename,frame,[cv2.IMWRITE_JPEG_QUALITY,100])
print('end')
#图片合成视频
import cv2
img=cv2.imread(r'C:\Users\Administrator\Desktop\1.1.jpg')
imginfo=img.shape
size=(imginfo[1],imginfo[0])
print(size)
videowrite=cv2.VideoWriter('2.mp4',-1,5,size)
for i in range(1,11):
filename='image'+str(i)+'.jpg'
img=cv2.imread(filename)
videowrite.write(img)
print('end')
# 3 data
data=np.vstack((rand1,rand2))
data=np.array(data,dtype='float32')
#svm 所有的数据都要有label
#[155,48] -- 0 女生 [152,53]----1 男生
#监督学习 (在学习的时候要知道他的标签) 0负样本 1 正样本
#4 训练(svm的训练)
svm=cv2.ml.SVM_create() #ml 机器学习模块 先创建了一个支持向量机,创建好之后,需要设置它的属性,这样它就创建好了,下来就是用它来进行训练与预测
#属性设置
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)#line
svm.setC(0.01)
#训练(参数设置好之后,使用SVM对数据进行训练)
result=svm.train(data,cv2.ml.ROW_SAMPLE,label)
#预测
pt_data=np.vstack([[167,55],[162,57]])#0 女生 1 男生
pt_data=np.array(pt_data,dtype='float32')
print(pt_data)
(par1,par2)=svm.predict(pt_data)
print(par1,par2)
##################很有用
#####对于文件夹下的图片统一尺寸,并保存到另外的文件夹下
import os
import time
from PIL import Image
def alter(path,object):
s = os.listdir(path)
count = 1
for i in s:
document = os.path.join(path,i)
img = Image.open(document)
out = img.resize((224,224))#224 *224是VGG16的结构模型输入大小
listStr = [str(int(time.time())), str(count)]
fileName = ''.join(listStr)
out.save(object+os.sep+'%s.jpg' % fileName,format='jpg')
count = count + 1
alter(r'C:\Users\Administrator\Desktop\火焰识别\训练样本\进行了数据增强的样本\最原始的样本\火焰图',r'C:\Users\Administrator\Desktop\火焰识别\训练样本\进行了数据增强的样本\最原始的样本\尺寸一致')
#很有用
###使用python批量修改文件名(按照顺序命名)
import os
class BatchRename():
def __init__(self):
self.path = r'C:\Users\Administrator\Desktop\火焰识别\训练样本\进行了数据增强的样本\最原始的样本\火焰图'
def rename(self):
filelist = os.listdir(self.path)
total_num = len(filelist)
i = 1
for item in filelist:
if item.endswith('.jpg'):
src = os.path.join(os.path.abspath(self.path), item)
dst = os.path.join(os.path.abspath(self.path), str(i) + '.jpg')
try:
os.rename(src, dst)
print('converting %s to %s ...' % (src, dst))
i = i + 1
except:
continue
if __name__ == '__main__':
demo = BatchRename()
demo.rename()
##对文件夹下的图片图像进行批量的水平翻转
import cv2
from glob2 import glob
for fn in glob(r'C:\Users\Administrator\Desktop\w\ww\www\*.jpg'): #确认文件格式
img=cv2.imread(fn)
horizontal_img=cv2.flip(img,1)#将原始图像进行批量翻转这样就获得了2倍的图片
splitName=fn.split(".")
newName=splitName[0]
cv2.imwrite(newName+'_flip.jpg',horizontal_img)
#在平移时改变大小(保证完整的信息)
import numpy as np
import cv2
from glob2 import glob
import numpy as np
from PIL import Image
# 大小改变
def transform_with_change_size(image,xoffset,yoffset):
rows = image.shape[0] + np.abs(yoffset)
cols = image.shape[1] + np.abs(xoffset)
dist = np.zeros((rows,cols,image.shape[2]),image.dtype)
for y in range(rows):
for x in range(cols):
new_x = x - xoffset
new_y = y - yoffset
if new_x >=0 and new_y >= 0 and new_x < cols and new_y < rows:
dist[y,x] = image[new_y,new_x]
return dist
for fn in glob(r'C:\Users\Administrator\Desktop\w\ww\fubenone\*.jpg'): #确认文件格式
img=cv2.imread(fn,1)
result = transform_with_change_size(img,100,100)
splitName=fn.split(".")
print(splitName[1])
cv2.imwrite('C:\\Users\\Administrator\\Desktop\\L\\'+splitName[1]+'.jpg',result)
#在平移时不改变大小
import numpy as np
import cv2
from glob2 import glob
import numpy as np
from PIL import Image
# 大小改变
def transform_without_change_size(image,xoffset,yoffset):
rows = image.shape[0]
cols = image.shape[1]
dist = np.zeros_like(image)
for y in range(rows):
for x in range(cols):
new_x = x - xoffset
new_y = y - yoffset
if new_x >=0 and new_y >= 0 and new_x < cols and new_y < rows:
dist[y,x] = image[new_y,new_x]
return dist
for fn in glob(r'C:\Users\Administrator\Desktop\w\ww\fubenthree\*.jpg'): #确认文件格式
img=cv2.imread(fn,1)
result = transform_with_change_size(img,100,100)
splitName=fn.split(".")
newName=splitName[0]
cv2.imwrite(newName+'_flip.jpg',result)
#进行旋转的程序(30度旋转)
import numpy as np
import cv2
from glob2 import glob
import numpy as np
from PIL import Image
def rotate(image, angle, center=None, scale=1.0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
for fn in glob(r'C:\Users\Administrator\Desktop\w\ww\fubenone\*.jpg'): #确认文件格式
img=cv2.imread(fn,1)
result = rotate(img,45)
splitName=fn.split(".")
print(splitName[1])
cv2.imwrite('C:\\Users\\Administrator\\Desktop\\L\\'+splitName[1]+'.jpg',result)
进行模型的保存
import tensorflow as tf
import os
import tarfile
import requests
#inception模型下载地址
inception_pretrain_model_url='http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
#模型存放地址
inception_pretrain_model_dir='inception_model'
if not os.path.exists(inception_pretrain_model_dir):
os.makedirs(inception_pretrain_model_dir)
#获取文件名,以及文件路径
filename=inception_pretrain_model_url.split('/')[-1]#这块获得的参数就是inception-2015-12-05.tgz
filepath=os.path.join(inception_pretrain_model_dir,filename)
#下载模型
if not os.path.exists(filepath):
print("download: ", filename)
r = requests.get(inception_pretrain_model_url, stream=True)
with open(filepath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print("finish: ", filename)
#解压文件
tarfile.open(filepath, 'r:gz').extractall(inception_pretrain_model_dir)
#模型结构存放文件
log_dir = 'inception_log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
#classify_image_graph_def.pb为google训练好的模型
inception_graph_def_file = os.path.join(inception_pretrain_model_dir, 'classify_image_graph_def.pb')
with tf.Session() as sess:
#创建一个图来存放google训练好的模型
with tf.gfile.FastGFile(inception_graph_def_file, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
#保存图的结构
writer = tf.summary.FileWriter(log_dir, sess.graph)
writer.close()