如何在OpenCV-ruby中获得检测到的面部的正确位置(x,y) [英] How to get correct position (x, y) of detected face in OpenCV-ruby

查看:121
本文介绍了如何在OpenCV-ruby中获得检测到的面部的正确位置(x,y)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用以下代码片段/代码来裁剪检测到的人脸:

I need to crop detected faces with this snippet/ codes :

image = IplImage::load("my_file.jpg")
sub = image.sub_rect(x,y, width, height)
sub.save_image("my_file_cropped.jpg")

所以我需要x,y,宽度和高度参数,但是如果我当前的代码是这样,我不知道要获得x和y参数:

So I need x, y, width and height params, but I have no idea to get x and y params if my current codes like this :

op = OpenCV::CvHaarClassifierCascade::load(OD_CLASSIFIER_FACE_PATH)
img = OpenCV::IplImage.load("test.jpg")

detector.detect_objects(op) do |region|
  color = OpenCV::CvColor::Blue
  props.rectangle! region.top_left, region.bottom_right, :color => color
end

真的需要帮助.

谢谢

推荐答案

所需的坐标位于region变量中,该变量是OpenCV:CvRect对象.您可以从该文档中查看此操作.该对象直接支持边界矩形的x,y,宽度和高度,这应该使您的任务非常容易.

The co-ordinates you need are in the region variable which is an OpenCV:CvRect object. You can see what this does from the documentation. The object directly supports x, y, width and height of the bounding rectangle, which should make your task quite easy.

您当前所在的位置:

image.sub_rect(x,y, width, height)

. . .如果变量region是具有所需坐标的OpenCV:CvRect对象,则可以只需使用其属性:

. . . if you have a variable region which is an OpenCV:CvRect object with the co-ordinates you want, you could simply use its properties:

image.sub_rect( region.x, region.y, region.width, region.height )

但是,甚至比这更好的是,sub_rect方法将把OpenCV:CvRect对象作为单个参数,并为您完成所有这些操作:

However, even better than that, the sub_rect method will take an OpenCV:CvRect object as a single parameter and do all this for you:

image.sub_rect( region )

因此,只需在第一个块中插入此修改,然后将对.save的调用插入到detect_objects块中即可:

So just insert this modification from the first block, and the call to .save into your detect_objects block:

op.detect_objects( img ) do |region|
  sub = img.sub_rect( region )
  sub.save_image("my_file_cropped.jpg")
end

请注意,这可能会多次写入文件(每检测到一张脸就写入一次).因此,如果您不知道图片中有多少张面孔,则可能需要每次生成一个新的文件名.放在一起,可能看起来像这样:

Note this may write to the file multiple times (once for each face detected). So if you don't know how many faces there are in the picture, you may want to generate a new file name each time. Putting it all together, that might look like this:

require 'opencv'
include OpenCV

input_name = "test"
output_name = "test_faces_"

CLASSIFIER_DATA = 'haarcascade_frontalface_alt.xml' # Or whatever

img = IplImage.load( input_name + ".jpg" )
detector = CvHaarClassifierCascade::load( CLASSIFIER_DATA )

face_id = 0
detector.detect_objects( img ) do |region|
  face_img = img.sub_rect( region )
  face_id += 1
  save_name = output_name + face_id.to_s + ".jpg"
  puts "Writing " + save_name
  face_img.save_image( save_name )
end

这篇关于如何在OpenCV-ruby中获得检测到的面部的正确位置(x,y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆