Skip to content

Instantly share code, notes, and snippets.

@RhetTbull
Created September 5, 2022 20:22
Show Gist options
  • Save RhetTbull/a17ecda8fd59fead7a18fdf1b6a2a509 to your computer and use it in GitHub Desktop.
Save RhetTbull/a17ecda8fd59fead7a18fdf1b6a2a509 to your computer and use it in GitHub Desktop.
Detect QR codes in python on MacOS using CoreImage API via PyObjC
"""Uses CoreImage API via PyObjC to detect QR Codes in images on MacOS.
This is a simple wrapper around the CIDetector API and only returns the text of the QR Code.
It does not return the location of the QR Code in the image.
Reference: https://developer.apple.com/documentation/coreimage/cidetector/detector_types?language=objc
"""
from typing import List
import objc
import Quartz
from Cocoa import NSURL
from Foundation import NSDictionary
def detect_qrcode(filepath: str) -> List[str]:
"""Detect QR Codes in images using CIDetector and return text of the found QR Codes"""
with objc.autorelease_pool():
context = Quartz.CIContext.contextWithOptions_(None)
options = NSDictionary.dictionaryWithDictionary_(
{"CIDetectorAccuracy": Quartz.CIDetectorAccuracyHigh}
)
detector = Quartz.CIDetector.detectorOfType_context_options_(
Quartz.CIDetectorTypeQRCode, context, options
)
results = []
input_url = NSURL.fileURLWithPath_(filepath)
input_image = Quartz.CIImage.imageWithContentsOfURL_(input_url)
features = detector.featuresInImage_(input_image)
if not features:
return []
for idx in range(features.count()):
feature = features.objectAtIndex_(idx)
results.append(feature.messageString())
return results
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: qrcodes.py <image file>")
sys.exit(1)
print(detect_qrcode(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment