python 建筑物识别_OpenCV+Python 指定物体识别

news/2024/6/15 10:30:04 标签: python 建筑物识别

本文介绍一种基于HoG+Pyramids+Sliding Windows+SVM的物体识别方法

基本流程

(1)确定最小检测物体,对原图img缩放,缩放比例为(滑动窗大小/最小物体大小)。

(2)缩放后的图片,构建金字塔。

(3)对金字塔的每一层,通过滑动窗获取patch(类似ROI的概念),对patch归一化处理,之后给训练好的物体检测器识别,将识别成功的窗口位置和概率保存。(特征使用HoG,分类算法使用SVM)

(4)将物体窗口映射到原图img中的物体位置,概率不变。

(5)NMS处理重叠窗口。

HoG

论文

HoG原理简书1

HoG原理简书2

Histogram of Oriented Gradients 方向梯度直方图,是特征描述符算法大家庭的一份子,家庭成员还有SIFT,SURF,ORB。

统计图像局部区域的梯度方向信息来作为该局部图像区域的表征。

基本步骤

灰度化。如果使用彩色图像,每个像素的梯度幅值取三个通道最大的,梯度方向取梯度幅值最大通道的方向。

归一化。对图像进行Gamma矫正,一般对每个像素的灰度值开根号。

计算每个像素的梯度。梯度方向一般分为9的区间(bin)。20°/bin for 无符号方向(0~180°),40°/bin for 有符号方向(0~360°)

统计每个Cell的梯度方向直方图。一般一个Cell是8*8个像素。9个特征值,对应9个bin。

统计每个Block的梯度方向直方图图。一般一个Block是2*2个Cell。36个特征值的向量,同时做归一化。

计算HoG特征向量。根据Block的总个数,生成总的HoG向量(36*n维向量)。

HoG存在的问题

不知道物体在图像的哪个位置。

不知道图像的尺度。

Image Pyramids

解决图像的尺度问题

图像金字塔简书1

OpenCV中图像金字塔的基本步骤

根据系数改变图像的大小。

平滑图像。

def resize(img, scaleFactor):

return cv2.resize(img, (int(img.shape[1] * (1 / scaleFactor)), int(img.shape[0] * (1 / scaleFactor))), interpolation=cv2.INTER_AREA)

def pyramid(image, scale=1.5, minSize=(200, 80)):

yield image

while True:

image = resize(image, scale)

if image.shape[0] < minSize[1] or image.shape[1] < minSize[0]:

break

yield image

Sliding Window

通过扫描图像的不同区域来解决图像中物体所在位置的问题。

def sliding_window(image, step, window_size):

for y in range(0, image.shape[0], step):

for x in range(0, image.shape[1], step):

yield (x, y, image[y:y + window_size[1], x:x + window_size[0]])

None-Maximam Suppression

NMS简书1

NMS解决的是如何在重叠区域中保留置信度最高的区域。

import numpy as np

# Malisiewicz et al.

# Python port by Adrian Rosebrock

def non_max_suppression_fast(boxes, overlapThresh):

# if there are no boxes, return an empty list

if len(boxes) == 0:

return []

# if the bounding boxes integers, convert them to floats --

# this is important since we'll be doing a bunch of divisions

if boxes.dtype.kind == "i":

boxes = boxes.astype("float")

# initialize the list of picked indexes

pick = []

# grab the coordinates of the bounding boxes

x1 = boxes[:, 0]

y1 = boxes[:, 1]

x2 = boxes[:, 2]

y2 = boxes[:, 3]

scores = boxes[:, 4]

# compute the area of the bounding boxes and sort the bounding

# boxes by the score/probability of the bounding box

area = (x2 - x1 + 1) * (y2 - y1 + 1)

idxs = np.argsort(scores)[::-1]

# keep looping while some indexes still remain in the indexes

# list

while len(idxs) > 0:

# grab the last index in the indexes list and add the

# index value to the list of picked indexes

last = len(idxs) - 1

i = idxs[last]

pick.append(i)

# find the largest (x, y) coordinates for the start of

# the bounding box and the smallest (x, y) coordinates

# for the end of the bounding box

xx1 = np.maximum(x1[i], x1[idxs[:last]])

yy1 = np.maximum(y1[i], y1[idxs[:last]])

xx2 = np.minimum(x2[i], x2[idxs[:last]])

yy2 = np.minimum(y2[i], y2[idxs[:last]])

# compute the width and height of the bounding box

w = np.maximum(0, xx2 - xx1 + 1)

h = np.maximum(0, yy2 - yy1 + 1)

# compute the ratio of overlap

overlap = (w * h) / area[idxs[:last]]

# delete all indexes from the index list that have

idxs = np.delete(idxs, np.concatenate(([last],

np.where(overlap > overlapThresh)[0])))

# return only the bounding boxes that were picked using the

# integer data type

return int(boxes[pick])

SVM

算法重点:找到离分隔超平面最近的点,确保它们离分隔面的距离尽可能远。这里点到分隔面的距离被称为间隔margin,这个margin尽可能的大。支持向量support vector就是离分隔超平面最近的那些点,我们要最大化支持向量到分隔面的距离。

实例

行人检测

import cv2

def draw_person(image, persont):

x, y, w, h = persont

cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)

img = cv2.imread("people1.jpg")

hog = cv2.HOGDescriptor()

hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

rects, weights = hog.detectMultiScale(img)

for person in rects:

draw_person(img, person)

cv2.imshow("people detection", img)

"""

detectMultiScale(img[, hitThreshold[, winStride[, padding[, scale[, finalThreshold[, useMeanshiftGrouping]]]]]]) -> foundLocations, foundWeights

. @brief Detects objects of different sizes in the input image. The detected objects are returned as a list

. of rectangles.

. @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.

. @param foundLocations Vector of rectangles where each rectangle contains the detected object.

. @param foundWeights Vector that will contain confidence values for each detected object.

. @param hitThreshold Threshold for the distance between features and SVM classifying plane.

. Usually it is 0 and should be specfied in the detector coefficients (as the last free coefficient).

. But if the free coefficient is omitted (which is allowed), you can specify it manually here.

. @param winStride Window stride. It must be a multiple of block stride. 步长

. @param padding Padding 填充

. @param scale Coefficient of the detection window increase.

. @param finalThreshold Final threshold

. @param useMeanshiftGrouping indicates grouping algorithm

"""

行人检测效果.png

检测一般物体

import cv2

import numpy as np

datapath = "TrainImages/"

def path(cls, i):

return "%s/%s%d.pgm" % (datapath, cls, i + 1)

def extract_sift(fn):

im = cv2.imread(fn, 0)

return extract.compute(im, detect.detect(im))[1]

def bow_features(fn):

im = cv2.imread(fn, 0)

return extract_bow.compute(im, detect.detect(im))

def predict(fn):

f = bow_features(fn)

p = svm.predict(f)

print(fn, "\t", p[1][0][0])

return p

pos, neg = "pos-", "neg-"

# 创建sift特征提取

detect = cv2.xfeatures2d.SIFT_create()

extract = cv2.xfeatures2d.SIFT_create()

# 创建基于flann的匹配器

flann_params = dict(algorithm=1, trees=5)

matcher = cv2.FlannBasedMatcher(flann_params, {})

# 创建bow训练器

bow_kmeans_trainer = cv2.BOWKMeansTrainer(40)

# 创建词袋模型

extract_bow = cv2.BOWImgDescriptorExtractor(extract, matcher)

# 为模型输入正负样本

for i in range(8):

bow_kmeans_trainer.add(extract_sift(path(pos, i)))

bow_kmeans_trainer.add(extract_sift(path(neg, i)))

# cluster函数,执行k-means分类,并且返回词汇。进一步制定extract_bow提取描述符

voc = bow_kmeans_trainer.cluster()

extract_bow.setVocabulary(voc)

# 创建2个数组,生成svm模型所需正负样本标签

traindata, trainlabels = [], []

for i in range(20):

traindata.extend(bow_features(path(pos, i)));

trainlabels.append(1)

traindata.extend(bow_features(path(neg, i)));

trainlabels.append(-1)

# 创建并训练一个svm模型

svm = cv2.ml.SVM_create()

svm.train(np.array(traindata), cv2.ml.ROW_SAMPLE, np.array(trainlabels))

# 测试两图

car, notcar = "car1", "car2"

car_img = cv2.imread(car)

notcar_img = cv2.imread(notcar)

car_predict = predict(car)

not_car_predict = predict(notcar)

font = cv2.FONT_HERSHEY_SIMPLEX

if car_predict[1][0][0] == 1.0:

cv2.putText(car_img, 'Car Detected', (10, 30), font, 1, (0, 255, 0), 2, cv2.LINE_AA)

if not_car_predict[1][0][0] == -1.0:

cv2.putText(notcar_img, 'Car Not Detected', (10, 30), font, 1, (0, 0, 255), 2, cv2.LINE_AA)

cv2.imshow('BOW + SVM Success', car_img)

cv2.imshow('BOW + SVM Failure', notcar_img)

cv2.waitKey(0)

cv2.destroyAllWindows()


http://www.niftyadmin.cn/n/1089236.html

相关文章

类加载器的加载范围

记过的东西总是容易忘&#xff0c;只好把它记录下来就当是一次灵魂与肉体的回忆吧&#xff01;&#xff01;&#xff01; 类加载器名称加载范围启动类加载器 Bootstrap ClassLoader存放在<JAVA_ HOME>\lib目录中&#xff0c;并且是虚拟机识别的类库&#xff0c;把它加载…

python列表的常用操作方法

python列表的常用操作方法 1. 列表添加数据&#xff1a; 1、list.append()添加对象&#xff1a; 2、list.extend(list1)扩展列表: 3、list.insert()插入对象&#xff1a; 4、list.copy()复制列表(python3) eg: list [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.insert(3, "…

python repl_Python 3.8新特征之asyncio REPL

前言我最近都在写一些Python 3.8的新功能介绍的文章&#xff0c;在自己的项目中也在提前体验新的Python版本。为什么我对这个Python 3.8这么有兴趣呢&#xff1f;主要是因为在Python 2停止官方维护的2020年来临之前&#xff0c;Python 3.8是最后一个大版本&#xff0c;虽然还没…

@ComponentScan中useDefaultFilters属性误解

事件还原 demo结构 com cap2 config Cap2MainConfig.java controller OrderController.java dao OrderDao.java server OrderService.java 代码 主要是测试bean是否被扫描&#xff08;里面的代码忽略) Controller public class OrderController { }Repository public cl…

spring使用@Autowired为抽象父类注入依赖

有时候为了管理或者避免不一致性&#xff0c;希望具体服务统一继承抽象父类&#xff0c;同时使用Autowired为抽象父类注入依赖。搜了了网上&#xff0c;有些解决方法实现实在不敢恭维&#xff0c;靠子类去注入依赖&#xff0c;那还有什么意义&#xff0c;如下&#xff1a; 父类…

编写一个文件加解密程序通过命令行完成加解密工作

import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.FileInputStream; import java.io.FileOutputStream;public class Encryption {private static final int numOfEncAndDec0x99;//加密解密密钥private static int dataOfFile0;…

@ComponentScan注解

示例 /*** ComponentScan 扫描组件* value 包扫描的路径* includeFilters Filter[] 指定扫描的时候只需要包含哪些组件* type FilterType.ANNOTATION 按照注解* classes {Service.class} 注解里面的Service* useDefaultFilters false 使用自定义扫描范围要改成false* 只扫…

solidworks入门实例画图_SolidWorks家用电子体温计,主要是放样曲面的使用SolidWslidworks家用电子体温计,主要是放样曲面的使用...

SolidWorks曲面建模实例&#xff0c;一款家用电子体温计&#xff0c;根据实物测绘建模&#xff0c;尺寸仅供大家参考&#xff0c;主要是放样曲面的应用&#xff0c;疫情在家&#xff0c;同样可以学习&#xff0c;还在等什么&#xff1f;赶紧动手试试吧&#xff01;效果图建模过…