Skip to content

Instantly share code, notes, and snippets.

@mseri
Last active December 10, 2021 08:56
Show Gist options
  • Save mseri/fc4af42ac539ddc37cf040dcbca6ed3d to your computer and use it in GitHub Desktop.
Save mseri/fc4af42ac539ddc37cf040dcbca6ed3d to your computer and use it in GitHub Desktop.
Set resolution for the picamera, I use it to select the field of view, see https://picamera.readthedocs.io/en/release-1.12/fov.html
//
// picam.swift
// picam
//
// Created by Marcello Seri on 31/05/2021.
//
import Foundation
import AVFoundation
let usage = """
picam
Set capture format for pi camera
USAGE:
picam [FLAGS] <index>
FLAGS:
-h --help Prints help information
-s --show Prints available options and their indices
ARGS:
<index> Index of the option to select. Will enter into an interactive prompt if not present.
"""
func show_formats(_ formats: [AVCaptureDevice.Format]) {
print("Compatible formats: ")
for (idx, format) in formats.enumerated() {
let desc = format.formatDescription
let dimensions = CMVideoFormatDescriptionGetDimensions(desc)
print(" \(idx). \(dimensions)")
}
}
func apply_setting(_ picam: AVCaptureDevice, _ sel: Int) throws -> Bool {
if sel >= 0 && sel < picam.formats.count {
let format = picam.formats[sel]
try picam.lockForConfiguration()
picam.activeFormat = format
picam.unlockForConfiguration()
print("Setup completed\n")
return true
} else {
print("Incorrect value\n")
return false
}
}
let arguments = CommandLine.arguments
if arguments.count > 2 {
print(usage)
exit(EXIT_FAILURE)
}
if arguments.count == 2 {
switch arguments[1] {
case "-h", "--help":
print(usage)
exit(EXIT_SUCCESS)
default:
// In all the other cases we need to have picam available
break
}
}
let ds = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.externalUnknown], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified)
let picam = ds.devices.first(where: {device in return device.localizedName.hasPrefix("UVC")})
if let picam = picam {
if arguments.count == 2 {
switch arguments[1] {
// Done above!
// case "-h", "--help":
// print(usage)
// exit(EXIT_SUCCESS)
case "-s", "--show":
show_formats(picam.formats)
exit(EXIT_SUCCESS)
default:
let sel = Int(arguments[1]) ?? -1
if sel == -1 {
print("Unparsable argument\n")
print(usage)
exit(EXIT_FAILURE)
}
if try apply_setting(picam, sel) {
exit(EXIT_SUCCESS)
} else {
print("An error has occurred\n")
exit(EXIT_FAILURE)
}
}
}
show_formats(picam.formats)
print("Type 'q' or 'quit' to exit")
while let input = readLine() {
guard !["quit", "q"].contains(input) else {
break
}
if let sel = Int(input.trimmingCharacters(in: .whitespacesAndNewlines)) {
if !(try apply_setting(picam, sel)) {
show_formats(picam.formats)
print("Type 'q' or 'quit' to exit")
}
} else { print("Unparsable value\n") }
}
} else {
print("Unable to initialize pi camera\n")
exit(EXIT_FAILURE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment