如何在OpenCV-ruby中获取检测到的面部的正确位置(x,y)
我需要使用此代码段/代码裁剪检测到的面孔:
image = IplImage::load("my_file.jpg") sub = image.sub_rect(x,y, width, height) sub.save_image("my_file_cropped.jpg")
所以我需要x,y,width和height参数,但如果我当前的代码是这样的话,我不知道如何获得x和y参数:
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,宽度和高度,这应该使您的任务非常容易。
你现在的位置:
image.sub_rect(x,y, width, height)
。 。 。 如果你有一个变量region
是一个OpenCV:CvRect
对象,你想要的坐标,你可以简单地使用它的属性:
image.sub_rect( region.x, region.y, region.width, region.height )
但是,甚至更好的是, sub_rect
方法将OpenCV:CvRect
对象作为单个参数,并为您完成所有这些:
image.sub_rect( region )
所以只需从第一个块插入此修改,并将.save
调用到您的detect_objects
块:
op.detect_objects( img ) do |region| sub = img.sub_rect( region ) sub.save_image("my_file_cropped.jpg") end
请注意,这可能会多次写入文件(检测到每个面部一次)。 因此,如果您不知道图片中有多少面,您可能希望每次都生成一个新文件名。 把它们放在一起,可能看起来像这样:
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