Just My Life & My Work

[iOS] 讀取影像中QRCode

過去嘗試過用相機掃描QRCode,現在想要讀取影像中QRCode,可以怎麼做呢?

iOS 讀取影像中QRCode.PNG

若有使用心動健康(名字暫定)的朋友,可以加我好友喔:)~

原來只要把UIImage轉成CIImage,CIDetector就能去偵測影像中的QRCode。

/**
 Theme: Detect Image from Image
 IDE: Xcode 9
 Language: Objective C
 Date: 106/11/16
 Author: HappyMan
 Blog: https://cg2010studio.com/
 */

-(NSArray *)detectQRCode:(UIImage *)image
{
    @autoreleasepool {
        NSLog(@"%@ :: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
        NSCAssert(image != nil, @"**Assertion Error** detectQRCode : image is nil");

        CIImage *ciImage = [[CIImage alloc] initWithImage:image]; // assuming underlying data is a CIImage
        //CIImage* ciImage = [CIImage initWithCGImage: UIImage.CGImage]; // to use if the underlying data is a CGImage

        NSDictionary* options;
        CIContext* context = [CIContext context];
        options = @{ CIDetectorAccuracy : CIDetectorAccuracyHigh }; // Slow but thorough
        //options = @{ CIDetectorAccuracy : CIDetectorAccuracyLow}; // Fast but superficial

        CIDetector* qrDetector = [CIDetector detectorOfType:CIDetectorTypeQRCode
                                                    context:context
                                                    options:options];
        if ([[ciImage properties] valueForKey:(NSString*) kCGImagePropertyOrientation] == nil) {
            options = @{ CIDetectorImageOrientation : @1};
        } else {
            options = @{ CIDetectorImageOrientation : [[ciImage properties] valueForKey:(NSString*) kCGImagePropertyOrientation]};
        }

        NSArray * features = [qrDetector featuresInImage:ciImage
                                                 options:options];

        return features;

    }
}

最需要注意的是UIImage目前直接轉為CIImage會回傳nil。

CIImage *ciImage = image.CIImage

要改成下列方式來轉換:

CIImage *ciImage = [[CIImage alloc] initWithImage:image];

小米運動加好友也是能從影像中讀取QRCode呢!

在debug的時候顯示CIImage:

iOS 讀取影像中QRCode

可以看到它在做矩陣運算~

參考:How to read QR code from static image

廣告

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: