iOS:从背景图中提取矩形图片

5
我正在进行一个实现,在其中我有一个矩形形状的图像在一个大背景图像中。我试图通过编程从大图像中检索矩形形状的图像,并从该特定矩形图像中检索文本信息。我尝试使用Open-CV第三方框架,但无法从大背景图像中检索矩形图像。请问有人能指导我如何实现吗?
更新:
我找到了Link,可以使用OpenCV查找正方形形状。我能否将其修改为查找矩形形状?有人能指导我吗?
最新更新:
我终于得到了代码,以下是它。
    - (cv::Mat)cvMatWithImage:(UIImage *)image
{
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
    CGFloat cols = image.size.width;
    CGFloat rows = image.size.height;

    cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels

    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,                 // Pointer to backing data
                                                    cols,                       // Width of bitmap
                                                    rows,                       // Height of bitmap
                                                    8,                          // Bits per component
                                                    cvMat.step[0],              // Bytes per row
                                                    colorSpace,                 // Colorspace
                                                    kCGImageAlphaNoneSkipLast |
                                                    kCGBitmapByteOrderDefault); // Bitmap info flags

    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);
    CGContextRelease(contextRef);

    return cvMat;
}
-(UIImage *)UIImageFromCVMat:(cv::Mat)cvMat
{
    NSData *data = [NSData dataWithBytes:cvMat.data length:cvMat.elemSize()*cvMat.total()];
    CGColorSpaceRef colorSpace;
    if ( cvMat.elemSize() == 1 ) {
        colorSpace = CGColorSpaceCreateDeviceGray();
    }
    else {
        colorSpace = CGColorSpaceCreateDeviceRGB();
    }

    //CFDataRef data;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData( (CFDataRef) data ); // It SHOULD BE (__bridge CFDataRef)data
    CGImageRef imageRef = CGImageCreate( cvMat.cols, cvMat.rows, 8, 8 * cvMat.elemSize(), cvMat.step[0], colorSpace, kCGImageAlphaNone|kCGBitmapByteOrderDefault, provider, NULL, false, kCGRenderingIntentDefault );
    UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease( imageRef );
    CGDataProviderRelease( provider );
    CGColorSpaceRelease( colorSpace );
    return finalImage;
}
-(void)forOpenCV
{
    imageView = [UIImage imageNamed:@"myimage.jpg"];
    if( imageView != nil )
    {
        cv::Mat tempMat = [imageView CVMat];

        cv::Mat greyMat = [self cvMatWithImage:imageView];
        cv::vector<cv::vector<cv::Point> > squares;

        cv::Mat img= [self debugSquares: squares: greyMat];

        imageView = [self UIImageFromCVMat: img];

        self.imageView.image = imageView;
    }
}

double angle( cv::Point pt1, cv::Point pt2, cv::Point pt0 ) {
    double dx1 = pt1.x - pt0.x;
    double dy1 = pt1.y - pt0.y;
    double dx2 = pt2.x - pt0.x;
    double dy2 = pt2.y - pt0.y;
    return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

- (cv::Mat) debugSquares: (std::vector<std::vector<cv::Point> >) squares : (cv::Mat &)image
{
    NSLog(@"%lu",squares.size());

    // blur will enhance edge detection

    //cv::Mat blurred(image);
    cv::Mat blurred = image.clone();
    medianBlur(image, blurred, 9);

    cv::Mat gray0(image.size(), CV_8U), gray;
    cv::vector<cv::vector<cv::Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&image, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); //

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, cv::Mat(), cv::Point(-1,-1));
            }
            else
            {
                gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            cv::vector<cv::Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                // approximate contour with accuracy proportional
                // to the contour perimeter
                approxPolyDP(cv::Mat(contours[i]), approx, arcLength(cv::Mat(contours[i]), true)*0.02, true);

                // Note: absolute value of an area is used because
                // area may be positive or negative - in accordance with the
                // contour orientation
                if (approx.size() == 4 &&
                    fabs(contourArea(cv::Mat(approx))) > 1000 &&
                    isContourConvex(cv::Mat(approx)))
                {
                    double maxCosine = 0;

                    for (int j = 2; j < 5; j++)
                    {
                        double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                        maxCosine = MAX(maxCosine, cosine);
                    }

                    if (maxCosine < 0.3)
                        squares.push_back(approx);
                }
            }
        }
    }

    NSLog(@"squares.size(): %lu",squares.size());


    for( size_t i = 0; i < squares.size(); i++ )
    {
        cv::Rect rectangle = boundingRect(cv::Mat(squares[i]));
        NSLog(@"rectangle.x: %d", rectangle.x);
        NSLog(@"rectangle.y: %d", rectangle.y);

        if(i==squares.size()-1)////Detecting Rectangle here
        {
            const cv::Point* p = &squares[i][0];

            int n = (int)squares[i].size();

            NSLog(@"%d",n);

            line(image, cv::Point(507,418), cv::Point(507+1776,418+1372), cv::Scalar(255,0,0),2,8);

            polylines(image, &p, &n, 1, true, cv::Scalar(255,255,0), 5, CV_AA);

            int fx1=rectangle.x;
                NSLog(@"X: %d", fx1);
            int fy1=rectangle.y;
                NSLog(@"Y: %d", fy1);
            int fx2=rectangle.x+rectangle.width;
                NSLog(@"Width: %d", fx2);
            int fy2=rectangle.y+rectangle.height;
                NSLog(@"Height: %d", fy2);

            line(image, cv::Point(fx1,fy1), cv::Point(fx2,fy2), cv::Scalar(0,0,255),2,8);

        }

    }

    return image;
}

谢谢。


嗨He Was,我的opencv没有任何错误。我现在已经包含了sqaures.cpp文件。但是,我如何从我的obj c代码中调用findSqaure方法并用于查找矩形?如果您能为我提供建议,那将非常感激。如果可以的话,让我们进一步聊聊这个问题,而不是在这里交流? - Getsy
您可以使用.mm文件而不是.m文件,在单个文件中混合使用C++和Objective C。我不知道这是否回答了您的问题。 - Victor Engel
嗨He Was,我已经在我的问题中更新了最新的代码,这是一个可工作的代码,请查看上面的问题。 - Getsy
另一个问题...你的输出是矩形(正如我所怀疑的)还是只有正方形? - foundry
抱歉回复晚了,因为我忙于其他事情。我粘贴的代码对你来说运行良好。我认为它可以检测矩形。无论我提供什么图像,在这一行“self.imageView.image = imageView;”处都会绘制相同的图像。我有点困惑,我们如何从给定的完整图像中找到每个矩形图像?如果我们可以进一步探讨这个问题并解决它,请告诉我。 - Getsy
显示剩余12条评论
2个回答

6
这里是一个完整的答案,使用一个小的包装类将C++代码与Objective-C代码分离开来。我不得不在stackoverflow上提出另一个问题来处理我的C++知识不足 - 但是我已经解决了我们需要使用squares.cpp示例代码清晰地接口化C++和Objective-C代码。目标是尽可能保持原始的C++代码,并将openCV的大部分工作保留在纯C++文件中以实现(可移植性)。我保留了我的原始答案,因为它似乎超出了编辑范围。完整的演示项目在github上
CVViewController.h / CVViewController.m
- 纯Objective-C - 通过WRAPPER与openCV C++代码通信... 它既不知道也不关心C++在包装器后面处理这些方法调用。
CVWrapper.h / CVWrapper.mm
- Objective-C++

尽可能地做得少,实际上只有两件事...

  • 调用UIImage objC++类别以转换为和从UIImage <> cv::Mat
  • 在CVViewController的obj-C方法和CVSquares c++(类)函数调用之间进行中介

CVSquares.h / CVSquares.cpp

  • 纯C++
  • CVSquares.cpp在类定义内部声明公共函数(在这种情况下,是一个静态函数)。
    这替代了原始文件中的main{}的工作。
  • 我们尽可能保持CVSquares.cpp接近于C++原始代码以实现可移植性。

CVViewController.m

//remove 'magic numbers' from original C++ source so we can manipulate them from obj-C
#define TOLERANCE 0.01
#define THRESHOLD 50
#define LEVELS 9

UIImage* image =
        [CVSquaresWrapper detectedSquaresInImage:self.image
                                       tolerance:TOLERANCE
                                       threshold:THRESHOLD
                                          levels:LEVELS];

CVSquaresWrapper.h

//  CVSquaresWrapper.h

#import <Foundation/Foundation.h>

@interface CVSquaresWrapper : NSObject

+ (UIImage*) detectedSquaresInImage:(UIImage*)image
                          tolerance:(CGFloat)tolerance
                          threshold:(NSInteger)threshold
                             levels:(NSInteger)levels;

@end

CVSquaresWrapper.mm

//  CVSquaresWrapper.mm
//  wrapper that talks to c++ and to obj-c classes

#import "CVSquaresWrapper.h"
#import "CVSquares.h"
#import "UIImage+OpenCV.h"

@implementation CVSquaresWrapper

+ (UIImage*) detectedSquaresInImage:(UIImage*) image
                          tolerance:(CGFloat)tolerance
                          threshold:(NSInteger)threshold
                             levels:(NSInteger)levels
{
    UIImage* result = nil;

        //convert from UIImage to cv::Mat openCV image format
        //this is a category on UIImage
    cv::Mat matImage = [image CVMat]; 


        //call the c++ class static member function
        //we want this function signature to exactly 
        //mirror the form of the calling method 
    matImage = CVSquares::detectedSquaresInImage (matImage, tolerance, threshold, levels);


        //convert back from cv::Mat openCV image format
        //to UIImage image format (category on UIImage)
    result = [UIImage imageFromCVMat:matImage]; 

    return result;
}

@end

CVSquares.h

//  CVSquares.h

#ifndef __OpenCVClient__CVSquares__
#define __OpenCVClient__CVSquares__

    //class definition
    //in this example we do not need a class 
    //as we have no instance variables and just one static function. 
    //We could instead just declare the function but this form seems clearer

class CVSquares
{
public:
    static cv::Mat detectedSquaresInImage (cv::Mat image, float tol, int threshold, int levels);
};

#endif /* defined(__OpenCVClient__CVSquares__) */

CVSquares.cpp

//  CVSquares.cpp

#include "CVSquares.h"

using namespace std;
using namespace cv;

static int thresh = 50, N = 11;
static float tolerance = 0.01;

    //declarations added so that we can move our 
    //public function to the top of the file
static void findSquares(  const Mat& image,   vector<vector<Point> >& squares );
static void drawSquares( Mat& image, vector<vector<Point> >& squares );

    //this public function performs the role of 
    //main{} in the original file (main{} is deleted)
cv::Mat CVSquares::detectedSquaresInImage (cv::Mat image, float tol, int threshold, int levels)
{
    vector<vector<Point> > squares;

    if( image.empty() )
        {
        cout << "Couldn't load " << endl;
        }

    tolerance = tol;
    thresh = threshold;
    N = levels;
    findSquares(image, squares);
    drawSquares(image, squares);

    return image;
}


// the rest of this file is identical to the original squares.cpp except:
// main{} is removed
// this line is removed from drawSquares: 
// imshow(wndname, image); 
// (obj-c will do the drawing)

UIImage+OpenCV.h

UIImage类别是一个ObjC++文件,其中包含了在UIImage和cv::Mat图像格式之间进行转换的代码。这就是您将两种方法-(UIImage *)UIImageFromCVMat:(cv::Mat)cvMat- (cv::Mat)cvMatWithImage:(UIImage *)image移动到的位置。
//UIImage+OpenCV.h

#import <UIKit/UIKit.h>

@interface UIImage (UIImage_OpenCV)

    //cv::Mat to UIImage
+ (UIImage *)imageFromCVMat:(cv::Mat&)cvMat;

    //UIImage to cv::Mat
- (cv::Mat)CVMat;


@end        

这里的方法实现与您的代码相同(虽然我们不传递UIImage进行转换,而是引用self)。

我尝试在Xcode中编译您的GitHub项目,但它无法编译,并在'operations.hpp'文件中的"CV_XADD"处显示错误,错误为"xxxx/Headers/core/operations.hpp:2313:17:{2313:17-2313:43}: error: expected '(' for function-style cast or type construction [1]"。 - Getsy
谢谢你告诉我,我会在另一台机器上从GitHub克隆并检查它。 - foundry
我已经在三个OSX版本(10.6、7和8),三个Xcode版本(4.2、4.4.1、4.5.2)和两台机器(2008年MacBook Pro,2010年Mac mini)上测试了该存储库。我只能在OSX10.6.8 / Xcode4.2上复制您的错误(在两台机器上都会产生错误)。这个设置的最大iOS目标是iOS5.0,但问题不在于此,因为我可以在OSX10.8.2 / Xcode4.5.2上成功地针对5.0并在5.0模拟器上运行。那么...你的设置是什么? - foundry
然后,您需要为您的设置编译openCV。由于您已经有了一些可用且正常工作的东西,因此请尝试将我的GitHub项目中包含的openCV库取出并替换为您的版本。您可能需要更改导入头文件的路径(在OpenCVSquares-Prefix.pch中使用#import <opencv2/opencv.hpp>)。祝你好运。 - foundry
嗨He Was,我需要问你一些问题,对于我来说,并非所有的图像都被矩形扣除了。我们能聊聊吗?如果可以,请提供给我Skype或Gtalk ID。 - Getsy
@Getsy,这个问题变得太啰嗦了,我的回答也变得很长。我建议你接受这个答案并发布一个新的问题帖子,其中包括你的样本图像等信息。你还应该尝试运行我的项目-滑块可能会帮助你感受变量如何影响结果(你可以使用工作库开始一个新项目,并将我的代码复制到其中,或者更好的是升级到10.7/10.8+Xcode4.5.2)。如果你仍然遇到问题,周六我可能可以通过was.he进行Skype交流。 - foundry

2
这里是部分答案。它并不完整,因为我正在尝试做完全相同的事情,但每一步都遇到了巨大的困难。我的objective-c知识很强,但C++非常薄弱。
你应该阅读这篇关于包装C++的指南
还有Ievgen Khvedchenia的计算机视觉演讲博客上的所有内容,特别是openCV教程。Ievgen还在github上发布了一个非常完整的项目来配合教程。
话虽如此,我仍然在努力解决openCV编译和顺畅运行的问题。
例如,Ievgen的教程作为一个完成的项目运行良好,但是如果我尝试从头开始重新创建它,我会遇到一些一直困扰我的openCV编译错误。这可能是由于我对C++及其与obj-C的集成的理解不够深入。
关于squares.cpp 你需要做的事情有:
  • 从squares.cpp中删除int main(int /*argc*/, char** /*argv*/)
  • 从drawSquares中删除imshow(wndname, image);(obj-c将进行绘制)
  • 创建一个名为squares.h的头文件
  • 在头文件中创建一个或两个公共函数,可以从obj-c(或obj-c/c++包装器)中调用
这是我目前所拥有的。
class squares
{
public:
         static cv::Mat& findSquares( const cv::Mat& image, cv::vector<cv::vector<cv::Point> >& squares );
         static cv::Mat& drawSquares( cv::Mat& image, const cv::vector<cv::vector<cv::Point> >& squares );

};

您应该能够将其简化为一个单一的方法,比如说processSquares,它只有一个输入参数cv::Mat& image和一个返回值cv::Mat& image。该方法将在.cpp文件中声明squares并调用findSquaresdrawSquares
包装器将接收一个UIImage输入图像,将其转换为cv::Mat image,使用该输入调用processSquares,并得到一个结果cv::Mat image。然后将该结果转换回NSImage并传递回objc调用函数。
这就是我们需要做的简要概述,我会尝试扩展这个答案,一旦我真正完成了其中的任何一个步骤!

嗨,He Was,我已经在我的问题中更新了最新的代码,这是一个可行的代码,请查看上面的问题。 - Getsy
@getsy,太好了,你成功了!我明天才能用真正的电脑,但我很想尽快运行你的结果。 - foundry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接