OpenCV-Python系列八:提取图像轮廓

OpenCV-Python系列八:提取图像轮廓,第1张

当你完成图像分割之后,图像轮廓检测往往可以进一步筛选你要的目标,OpenCV中可以使用cv2.findContours来得到轮廓。

补充

再不少场景中,找轮廓的最小外接矩形是基本需求,opencv中minAreaRect得到的是一个带有旋转角度信息的rect,可以使用cv2.boxPoints(rect)来将其转为矩形的四个顶点坐标(浮点类型).你也可以使用cv2.polylines来绘制这样的轮廓信息

注意findContours参数的变化,在opencv4中,返回值只有contours和hierarchy ,这一点与opencv3中不同。对与轮廓的层级结构,比较难用,虽然可以通过轮廓的层级结构来进行索引你需要的轮廓,不过对于大部分机器视觉应用场景,二值化的结果有时候很难预料,单单通过这种层级关系索引,非常容易出错。所以,只找最外部结构的 cv2.RETR_EXTERNAL 是不是真香呢?

处理cv2.approxPolyDP()外,你也可以使用cv2.convexHull来求轮廓的近似凸包,其中凸形状内部--任意两点连线都在该形状内部。

clockwise :默认为False,即轮廓为逆时针方向进行排列;

returnPoints :设置为False会返回与凸包上对应的轮廓的点索引值,设置为True,则会返回凸包上的点坐标集,默认为True

对于opencv-python的提取图像轮廓部分有问题欢迎留言, Have Fun With OpenCV-Python, 下期见。

主要步骤1.读取一幅图片,并且对其进行二值化。2.对其进行形态学处理,减少孔洞等次要特征,保留其主要特征。3.进行边缘提取。4.进行形状轮廓匹配,得到其匹配值,从而判断是否是同一个形状。

下面是演示代码:

#include

#include"opencv2/opencv.hpp"

usingnamespacestd

usingnamespacecv

intmain()

{

Matk=imread("E:/TestGit/8.jpg",0)

Matf

Matk1=imread("E:/TestGit/9.jpg",0)

Matf1

threshold(k,f,50,255,THRESH_BINARY)//对图像进行二值化

threshold(k1,f1,50,255,THRESH_BINARY)

Matcloserect=getStructuringElement(MORPH_RECT,Size(3,3))//进行结构算子生成

morphologyEx(f,f,MORPH_OPEN,closerect)

morphologyEx(f1,f1,MORPH_OPEN,closerect)//进行形态学开运算

Matdst=Mat::zeros(k.rows,k.cols,CV_8UC3)

Matdst1=Mat::zeros(k1.rows,k1.cols,CV_8UC3)

vector>w,w1

vectorhierarchy,hierarchy1

findContours(f,w,hierarchy,RETR_CCOMP,CHAIN_APPROX_SIMPLE)//提取轮廓元素

findContours(f1,w1,hierarchy1,RETR_CCOMP,CHAIN_APPROX_SIMPLE)

FileStoragefs("f.dat",FileStorage::WRITE)

fs

intidx=0

doubleffff=matchShapes(w[0],w1[0],CV_CONTOURS_MATCH_I3,1.0)//进行轮廓匹配

std::cout

system("pause")

return0

}

这样,我们就得到了轮廓边缘的提取和匹配,满足了需要。而不同的算子具有不同的匹配算子方法。

整个项目的结构图:

编写DetectFaceDemo.java,代码如下:

[java] view

plaincopyprint?

package com.njupt.zhb.test

import org.opencv.core.Core

import org.opencv.core.Mat

import org.opencv.core.MatOfRect

import org.opencv.core.Point

import org.opencv.core.Rect

import org.opencv.core.Scalar

import org.opencv.highgui.Highgui

import org.opencv.objdetect.CascadeClassifier

//

// Detects faces in an image, draws boxes around them, and writes the results

// to "faceDetection.png".

//

public class DetectFaceDemo {

public void run() {

System.out.println("\nRunning DetectFaceDemo")

System.out.println(getClass().getResource("lbpcascade_frontalface.xml").getPath())

// Create a face detector from the cascade file in the resources

// directory.

//CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("lbpcascade_frontalface.xml").getPath())

//Mat image = Highgui.imread(getClass().getResource("lena.png").getPath())

//注意:源程序的路径会多打印一个‘/’,因此总是出现如下错误

/*

* Detected 0 faces Writing faceDetection.png libpng warning: Image

* width is zero in IHDR libpng warning: Image height is zero in IHDR

* libpng error: Invalid IHDR data

*/

//因此,我们将第一个字符去掉

String xmlfilePath=getClass().getResource("lbpcascade_frontalface.xml").getPath().substring(1)

CascadeClassifier faceDetector = new CascadeClassifier(xmlfilePath)

Mat image = Highgui.imread(getClass().getResource("we.jpg").getPath().substring(1))

// Detect faces in the image.

// MatOfRect is a special container class for Rect.

MatOfRect faceDetections = new MatOfRect()

faceDetector.detectMultiScale(image, faceDetections)

System.out.println(String.format("Detected %s faces", faceDetections.toArray().length))

// Draw a bounding box around each face.

for (Rect rect : faceDetections.toArray()) {

Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0))

}

// Save the visualized detection.

String filename = "faceDetection.png"

System.out.println(String.format("Writing %s", filename))

Highgui.imwrite(filename, image)

}

}

package com.njupt.zhb.test

import org.opencv.core.Core

import org.opencv.core.Mat

import org.opencv.core.MatOfRect

import org.opencv.core.Point

import org.opencv.core.Rect

import org.opencv.core.Scalar

import org.opencv.highgui.Highgui

import org.opencv.objdetect.CascadeClassifier

//

// Detects faces in an image, draws boxes around them, and writes the results

// to "faceDetection.png".

//

public class DetectFaceDemo {

public void run() {

System.out.println("\nRunning DetectFaceDemo")

System.out.println(getClass().getResource("lbpcascade_frontalface.xml").getPath())

// Create a face detector from the cascade file in the resources

// directory.

//CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("lbpcascade_frontalface.xml").getPath())

//Mat image = Highgui.imread(getClass().getResource("lena.png").getPath())

//注意:源程序的路径会多打印一个‘/’,因此总是出现如下错误

/*

* Detected 0 faces Writing faceDetection.png libpng warning: Image

* width is zero in IHDR libpng warning: Image height is zero in IHDR

* libpng error: Invalid IHDR data

*/

//因此,我们将第一个字符去掉

String xmlfilePath=getClass().getResource("lbpcascade_frontalface.xml").getPath().substring(1)

CascadeClassifier faceDetector = new CascadeClassifier(xmlfilePath)

Mat image = Highgui.imread(getClass().getResource("we.jpg").getPath().substring(1))

// Detect faces in the image.

// MatOfRect is a special container class for Rect.

MatOfRect faceDetections = new MatOfRect()

faceDetector.detectMultiScale(image, faceDetections)

System.out.println(String.format("Detected %s faces", faceDetections.toArray().length))

// Draw a bounding box around each face.

for (Rect rect : faceDetections.toArray()) {

Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0))

}

// Save the visualized detection.

String filename = "faceDetection.png"

System.out.println(String.format("Writing %s", filename))

Highgui.imwrite(filename, image)

}

}

3.编写测试类:

[java] view

plaincopyprint?

package com.njupt.zhb.test

public class TestMain {

public static void main(String[] args) {

System.out.println("Hello, OpenCV")

// Load the native library.

System.loadLibrary("opencv_java246")

new DetectFaceDemo().run()

}

}

//运行结果:

//Hello, OpenCV

//

//Running DetectFaceDemo

///E:/eclipse_Jee/workspace/JavaOpenCV246/bin/com/njupt/zhb/test/lbpcascade_frontalface.xml

//Detected 8 faces

//Writing faceDetection.png

package com.njupt.zhb.test

public class TestMain {

public static void main(String[] args) {

System.out.println("Hello, OpenCV")

// Load the native library.

System.loadLibrary("opencv_java246")

new DetectFaceDemo().run()

}

}

//运行结果:

//Hello, OpenCV

//

//Running DetectFaceDemo

///E:/eclipse_Jee/workspace/JavaOpenCV246/bin/com/njupt/zhb/test/lbpcascade_frontalface.xml

//Detected 8 faces

//Writing faceDetection.png


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/8118308.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-13
下一篇2023-04-13

发表评论

登录后才能评论

评论列表(0条)

    保存