summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/ipa/raspberrypi/controller/rpi/agc.cpp90
1 files changed, 47 insertions, 43 deletions
diff --git a/src/ipa/raspberrypi/controller/rpi/agc.cpp b/src/ipa/raspberrypi/controller/rpi/agc.cpp
index df4d3647..8079345b 100644
--- a/src/ipa/raspberrypi/controller/rpi/agc.cpp
+++ b/src/ipa/raspberrypi/controller/rpi/agc.cpp
@@ -9,16 +9,20 @@
#include "linux/bcm2835-isp.h"
+#include "libcamera/internal/log.h"
+
#include "../awb_status.h"
#include "../device_status.h"
#include "../histogram.hpp"
-#include "../logging.hpp"
#include "../lux_status.h"
#include "../metadata.hpp"
#include "agc.hpp"
using namespace RPiController;
+using namespace libcamera;
+
+LOG_DEFINE_CATEGORY(RPiAgc)
#define NAME "rpi.agc"
@@ -128,7 +132,7 @@ static std::string read_constraint_modes(
void AgcConfig::Read(boost::property_tree::ptree const &params)
{
- RPI_LOG("AgcConfig");
+ LOG(RPiAgc, Debug) << "AgcConfig";
default_metering_mode = read_metering_modes(
metering_modes, params.get_child("metering_modes"));
default_exposure_mode = read_exposure_modes(
@@ -166,7 +170,7 @@ char const *Agc::Name() const
void Agc::Read(boost::property_tree::ptree const &params)
{
- RPI_LOG("Agc");
+ LOG(RPiAgc, Debug) << "Agc";
config_.Read(params);
// Set the config's defaults (which are the first ones it read) as our
// current modes, until someone changes them. (they're all known to
@@ -254,15 +258,15 @@ void Agc::Prepare(Metadata *image_metadata)
status.digital_gain =
status_.total_exposure_value /
actual_exposure;
- RPI_LOG("Want total exposure " << status_.total_exposure_value);
+ LOG(RPiAgc, Debug) << "Want total exposure " << status_.total_exposure_value;
// Never ask for a gain < 1.0, and also impose
// some upper limit. Make it customisable?
status.digital_gain = std::max(
1.0,
std::min(status.digital_gain, 4.0));
- RPI_LOG("Actual exposure " << actual_exposure);
- RPI_LOG("Use digital_gain " << status.digital_gain);
- RPI_LOG("Effective exposure " << actual_exposure * status.digital_gain);
+ LOG(RPiAgc, Debug) << "Actual exposure " << actual_exposure;
+ LOG(RPiAgc, Debug) << "Use digital_gain " << status.digital_gain;
+ LOG(RPiAgc, Debug) << "Effective exposure " << actual_exposure * status.digital_gain;
// Decide whether AEC/AGC has converged.
// Insist AGC is steady for MAX_LOCK_COUNT
// frames before we say we are "locked".
@@ -285,11 +289,11 @@ void Agc::Prepare(Metadata *image_metadata)
status.target_exposure_value
- 1.5 * err)
lock_count_ = lock_count;
- RPI_LOG("Lock count: " << lock_count_);
+ LOG(RPiAgc, Debug) << "Lock count: " << lock_count_;
}
}
} else
- RPI_LOG(Name() << ": no device metadata");
+ LOG(RPiAgc, Debug) << Name() << ": no device metadata";
status.locked = lock_count_ >= MAX_LOCK_COUNT;
//printf("%s\n", status.locked ? "+++++++++" : "-");
image_metadata->Set("agc.status", status);
@@ -343,9 +347,9 @@ void Agc::housekeepConfig()
status_.fixed_analogue_gain = fixed_analogue_gain_;
status_.flicker_period = flicker_period_;
}
- RPI_LOG("ev " << status_.ev << " fixed_shutter "
- << status_.fixed_shutter << " fixed_analogue_gain "
- << status_.fixed_analogue_gain);
+ LOG(RPiAgc, Debug) << "ev " << status_.ev << " fixed_shutter "
+ << status_.fixed_shutter << " fixed_analogue_gain "
+ << status_.fixed_analogue_gain;
// Make sure the "mode" pointers point to the up-to-date things, if
// they've changed.
if (strcmp(new_metering_mode_name.c_str(), status_.metering_mode)) {
@@ -376,10 +380,10 @@ void Agc::housekeepConfig()
copy_string(new_constraint_mode_name, status_.constraint_mode,
sizeof(status_.constraint_mode));
}
- RPI_LOG("exposure_mode "
- << new_exposure_mode_name << " constraint_mode "
- << new_constraint_mode_name << " metering_mode "
- << new_metering_mode_name);
+ LOG(RPiAgc, Debug) << "exposure_mode "
+ << new_exposure_mode_name << " constraint_mode "
+ << new_constraint_mode_name << " metering_mode "
+ << new_metering_mode_name;
}
void Agc::fetchCurrentExposure(Metadata *image_metadata)
@@ -404,7 +408,7 @@ static double compute_initial_Y(bcm2835_isp_stats *stats, Metadata *image_metada
struct AwbStatus awb;
awb.gain_r = awb.gain_g = awb.gain_b = 1.0; // in case no metadata
if (image_metadata->Get("awb.status", awb) != 0)
- RPI_WARN("Agc: no AWB status found");
+ LOG(RPiAgc, Warning) << "Agc: no AWB status found";
double Y_sum = 0, weight_sum = 0;
for (int i = 0; i < AGC_STATS_SIZE; i++) {
if (regions[i].counted == 0)
@@ -443,7 +447,7 @@ void Agc::computeGain(bcm2835_isp_stats *statistics, Metadata *image_metadata,
struct LuxStatus lux = {};
lux.lux = 400; // default lux level to 400 in case no metadata found
if (image_metadata->Get("lux.status", lux) != 0)
- RPI_WARN("Agc: no lux level found");
+ LOG(RPiAgc, Warning) << "Agc: no lux level found";
Histogram h(statistics->hist[0].g_hist, NUM_HISTOGRAM_BINS);
double ev_gain = status_.ev * config_.base_ev;
// The initial gain and target_Y come from some of the regions. After
@@ -454,28 +458,28 @@ void Agc::computeGain(bcm2835_isp_stats *statistics, Metadata *image_metadata,
double initial_Y = compute_initial_Y(statistics, image_metadata,
metering_mode_->weights);
gain = std::min(10.0, target_Y / (initial_Y + .001));
- RPI_LOG("Initially Y " << initial_Y << " target " << target_Y
- << " gives gain " << gain);
+ LOG(RPiAgc, Debug) << "Initially Y " << initial_Y << " target " << target_Y
+ << " gives gain " << gain;
for (auto &c : *constraint_mode_) {
double new_target_Y;
double new_gain =
constraint_compute_gain(c, h, lux.lux, ev_gain,
new_target_Y);
- RPI_LOG("Constraint has target_Y "
- << new_target_Y << " giving gain " << new_gain);
+ LOG(RPiAgc, Debug) << "Constraint has target_Y "
+ << new_target_Y << " giving gain " << new_gain;
if (c.bound == AgcConstraint::Bound::LOWER &&
new_gain > gain) {
- RPI_LOG("Lower bound constraint adopted");
+ LOG(RPiAgc, Debug) << "Lower bound constraint adopted";
gain = new_gain, target_Y = new_target_Y;
} else if (c.bound == AgcConstraint::Bound::UPPER &&
new_gain < gain) {
- RPI_LOG("Upper bound constraint adopted");
+ LOG(RPiAgc, Debug) << "Upper bound constraint adopted";
gain = new_gain, target_Y = new_target_Y;
}
}
- RPI_LOG("Final gain " << gain << " (target_Y " << target_Y << " ev "
- << status_.ev << " base_ev " << config_.base_ev
- << ")");
+ LOG(RPiAgc, Debug) << "Final gain " << gain << " (target_Y " << target_Y << " ev "
+ << status_.ev << " base_ev " << config_.base_ev
+ << ")";
}
void Agc::computeTargetExposure(double gain)
@@ -494,7 +498,7 @@ void Agc::computeTargetExposure(double gain)
: exposure_mode_->gain.back());
target_.total_exposure = std::min(target_.total_exposure,
max_total_exposure);
- RPI_LOG("Target total_exposure " << target_.total_exposure);
+ LOG(RPiAgc, Debug) << "Target total_exposure " << target_.total_exposure;
}
bool Agc::applyDigitalGain(Metadata *image_metadata, double gain,
@@ -509,9 +513,9 @@ bool Agc::applyDigitalGain(Metadata *image_metadata, double gain,
std::min(awb.gain_g, awb.gain_b));
dg *= std::max(1.0, 1.0 / min_gain);
} else
- RPI_WARN("Agc: no AWB status found");
- RPI_LOG("after AWB, target dg " << dg << " gain " << gain
- << " target_Y " << target_Y);
+ LOG(RPiAgc, Warning) << "Agc: no AWB status found";
+ LOG(RPiAgc, Debug) << "after AWB, target dg " << dg << " gain " << gain
+ << " target_Y " << target_Y;
// Finally, if we're trying to reduce exposure but the target_Y is
// "close" to 1.0, then the gain computed for that constraint will be
// only slightly less than one, because the measured Y can never be
@@ -523,9 +527,9 @@ bool Agc::applyDigitalGain(Metadata *image_metadata, double gain,
gain < sqrt(target_Y);
if (desaturate)
dg /= config_.fast_reduce_threshold;
- RPI_LOG("Digital gain " << dg << " desaturate? " << desaturate);
+ LOG(RPiAgc, Debug) << "Digital gain " << dg << " desaturate? " << desaturate;
target_.total_exposure_no_dg = target_.total_exposure / dg;
- RPI_LOG("Target total_exposure_no_dg " << target_.total_exposure_no_dg);
+ LOG(RPiAgc, Debug) << "Target total_exposure_no_dg " << target_.total_exposure_no_dg;
return desaturate;
}
@@ -560,8 +564,8 @@ void Agc::filterExposure(bool desaturate)
filtered_.total_exposure * config_.fast_reduce_threshold)
filtered_.total_exposure_no_dg = filtered_.total_exposure *
config_.fast_reduce_threshold;
- RPI_LOG("After filtering, total_exposure " << filtered_.total_exposure <<
- " no dg " << filtered_.total_exposure_no_dg);
+ LOG(RPiAgc, Debug) << "After filtering, total_exposure " << filtered_.total_exposure
+ << " no dg " << filtered_.total_exposure_no_dg;
}
void Agc::divvyupExposure()
@@ -602,8 +606,8 @@ void Agc::divvyupExposure()
}
}
}
- RPI_LOG("Divided up shutter and gain are " << shutter_time << " and "
- << analogue_gain);
+ LOG(RPiAgc, Debug) << "Divided up shutter and gain are " << shutter_time << " and "
+ << analogue_gain;
// Finally adjust shutter time for flicker avoidance (require both
// shutter and gain not to be fixed).
if (status_.fixed_shutter == 0.0 &&
@@ -621,8 +625,8 @@ void Agc::divvyupExposure()
exposure_mode_->gain.back());
shutter_time = new_shutter_time;
}
- RPI_LOG("After flicker avoidance, shutter "
- << shutter_time << " gain " << analogue_gain);
+ LOG(RPiAgc, Debug) << "After flicker avoidance, shutter "
+ << shutter_time << " gain " << analogue_gain;
}
filtered_.shutter = shutter_time;
filtered_.analogue_gain = analogue_gain;
@@ -641,10 +645,10 @@ void Agc::writeAndFinish(Metadata *image_metadata, bool desaturate)
// Write to metadata as well, in case anyone wants to update the camera
// immediately.
image_metadata->Set("agc.status", status_);
- RPI_LOG("Output written, total exposure requested is "
- << filtered_.total_exposure);
- RPI_LOG("Camera exposure update: shutter time " << filtered_.shutter <<
- " analogue gain " << filtered_.analogue_gain);
+ LOG(RPiAgc, Debug) << "Output written, total exposure requested is "
+ << filtered_.total_exposure;
+ LOG(RPiAgc, Debug) << "Camera exposure update: shutter time " << filtered_.shutter
+ << " analogue gain " << filtered_.analogue_gain;
}
// Register algorithm with the system.
'n559' href='#n559'>559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
#!/usr/bin/env python3
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (C) 2019, Raspberry Pi Ltd
#
# ctt.py - camera tuning tool

import os
import sys
from ctt_image_load import *
from ctt_ccm import *
from ctt_awb import *
from ctt_alsc import *
from ctt_lux import *
from ctt_noise import *
from ctt_geq import *
from ctt_pretty_print_json import pretty_print
import random
import json
import re

"""
This file houses the camera object, which is used to perform the calibrations.
The camera object houses all the calibration images as attributes in two lists:
    - imgs (macbeth charts)
    - imgs_alsc (alsc correction images)
Various calibrations are methods of the camera object, and the output is stored
in a dictionary called self.json.
Once all the caibration has been completed, the Camera.json is written into a
json file.
The camera object initialises its json dictionary by reading from a pre-written
blank json file. This has been done to avoid reproducing the entire json file
in the code here, thereby avoiding unecessary clutter.
"""


"""
Get the colour and lux values from the strings of each inidvidual image
"""
def get_col_lux(string):
    """
    Extract colour and lux values from filename
    """
    col = re.search(r'([0-9]+)[kK](\.(jpg|jpeg|brcm|dng)|_.*\.(jpg|jpeg|brcm|dng))$', string)
    lux = re.search(r'([0-9]+)[lL](\.(jpg|jpeg|brcm|dng)|_.*\.(jpg|jpeg|brcm|dng))$', string)
    try:
        col = col.group(1)
    except AttributeError:
        """
        Catch error if images labelled incorrectly and pass reasonable defaults
        """
        return None, None
    try:
        lux = lux.group(1)
    except AttributeError:
        """
        Catch error if images labelled incorrectly and pass reasonable defaults
        Still returns colour if that has been found.
        """
        return col, None
    return int(col), int(lux)


"""
Camera object that is the backbone of the tuning tool.
Input is the desired path of the output json.
"""
class Camera:
    def __init__(self, jfile):
        self.path = os.path.dirname(os.path.expanduser(__file__)) + '/'
        if self.path == '/':
            self.path = ''
        self.imgs = []
        self.imgs_alsc = []
        self.log = 'Log created : ' + time.asctime(time.localtime(time.time()))
        self.log_separator = '\n'+'-'*70+'\n'
        self.jf = jfile
        """
        initial json dict populated by uncalibrated values
        """
        self.json = {
            "rpi.black_level": {
                "black_level": 4096
            },
            "rpi.dpc": {
            },
            "rpi.lux": {
                "reference_shutter_speed": 10000,
                "reference_gain": 1,
                "reference_aperture": 1.0
            },
            "rpi.noise": {
            },
            "rpi.geq": {
            },
            "rpi.sdn": {
            },
            "rpi.awb": {
                "priors": [
                    {"lux": 0, "prior": [2000, 1.0, 3000, 0.0, 13000, 0.0]},
                    {"lux": 800, "prior": [2000, 0.0, 6000, 2.0, 13000, 2.0]},
                    {"lux": 1500, "prior": [2000, 0.0, 4000, 1.0, 6000, 6.0, 6500, 7.0, 7000, 1.0, 13000, 1.0]}
                ],
                "modes": {
                    "auto": {"lo": 2500, "hi": 8000},
                    "incandescent": {"lo": 2500, "hi": 3000},
                    "tungsten": {"lo": 3000, "hi": 3500},
                    "fluorescent": {"lo": 4000, "hi": 4700},
                    "indoor": {"lo": 3000, "hi": 5000},
                    "daylight": {"lo": 5500, "hi": 6500},
                    "cloudy": {"lo": 7000, "hi": 8600}
                },
                "bayes": 1
            },
            "rpi.agc": {
                "metering_modes": {
                    "centre-weighted": {
                        "weights": [3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0]
                    },
                    "spot": {
                        "weights": [2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                    },
                    "matrix": {
                        "weights": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
                    }
                },
                "exposure_modes": {
                    "normal": {
                        "shutter": [100, 10000, 30000, 60000, 120000],
                        "gain": [1.0, 2.0, 4.0, 6.0, 6.0]
                    },
                    "short": {
                        "shutter": [100, 5000, 10000, 20000, 120000],
                        "gain": [1.0, 2.0, 4.0, 6.0, 6.0]
                    }
                },
                "constraint_modes": {
                    "normal": [
                        {"bound": "LOWER", "q_lo": 0.98, "q_hi": 1.0, "y_target": [0, 0.5, 1000, 0.5]}
                    ],
                    "highlight": [
                        {"bound": "LOWER", "q_lo": 0.98, "q_hi": 1.0, "y_target": [0, 0.5, 1000, 0.5]},
                        {"bound": "UPPER", "q_lo": 0.98, "q_hi": 1.0, "y_target": [0, 0.8, 1000, 0.8]}
                    ]
                },
                "y_target": [0, 0.16, 1000, 0.165, 10000, 0.17]
            },
            "rpi.alsc": {
                'omega': 1.3,
                'n_iter': 100,
                'luminance_strength': 0.7,
            },
            "rpi.contrast": {
                "ce_enable": 1,
                "gamma_curve": [
                    0,     0,
                    1024,  5040,
                    2048,  9338,
                    3072,  12356,
                    4096,  15312,
                    5120,  18051,
                    6144,  20790,
                    7168,  23193,
                    8192,  25744,
                    9216,  27942,
                    10240, 30035,
                    11264, 32005,
                    12288, 33975,
                    13312, 35815,
                    14336, 37600,
                    15360, 39168,
                    16384, 40642,
                    18432, 43379,
                    20480, 45749,
                    22528, 47753,
                    24576, 49621,
                    26624, 51253,
                    28672, 52698,
                    30720, 53796,
                    32768, 54876,
                    36864, 57012,
                    40960, 58656,
                    45056, 59954,
                    49152, 61183,
                    53248, 62355,
                    57344, 63419,
                    61440, 64476,
                    65535, 65535
                ]
            },
            "rpi.ccm": {
            },
            "rpi.sharpen": {
            }
        }

    """
    Perform colour correction calibrations by comparing macbeth patch colours
    to standard macbeth chart colours.
    """
    def ccm_cal(self, do_alsc_colour):
        if 'rpi.ccm' in self.disable:
            return 1
        print('\nStarting CCM calibration')
        self.log_new_sec('CCM')
        """
        if image is greyscale then CCm makes no sense
        """
        if self.grey:
            print('\nERROR: Can\'t do CCM on greyscale image!')
            self.log += '\nERROR: Cannot perform CCM calibration '
            self.log += 'on greyscale image!\nCCM aborted!'
            del self.json['rpi.ccm']
            return 0
        a = time.time()
        """
        Check if alsc tables have been generated, if not then do ccm without
        alsc
        """
        if ("rpi.alsc" not in self.disable) and do_alsc_colour:
            """
            case where ALSC colour has been done, so no errors should be
            expected...
            """
            try:
                cal_cr_list = self.json['rpi.alsc']['calibrations_Cr']
                cal_cb_list = self.json['rpi.alsc']['calibrations_Cb']
                self.log += '\nALSC tables found successfully'
            except KeyError:
                cal_cr_list, cal_cb_list = None, None
                print('WARNING! No ALSC tables found for CCM!')
                print('Performing CCM calibrations without ALSC correction...')
                self.log += '\nWARNING: No ALSC tables found.\nCCM calibration '
                self.log += 'performed without ALSC correction...'
        else:
            """
            case where config options result in CCM done without ALSC colour tables
            """
            cal_cr_list, cal_cb_list = None, None
            self.log += '\nWARNING: No ALSC tables found.\nCCM calibration '
            self.log += 'performed without ALSC correction...'

        """
        Do CCM calibration
        """
        try:
            ccms = ccm(self, cal_cr_list, cal_cb_list)
        except ArithmeticError:
            print('ERROR: Matrix is singular!\nTake new pictures and try again...')
            self.log += '\nERROR: Singular matrix encountered during fit!'
            self.log += '\nCCM aborted!'
            return 1
        """
        Write output to json
        """
        self.json['rpi.ccm']['ccms'] = ccms
        self.log += '\nCCM calibration written to json file'
        print('Finished CCM calibration')

    """
    Auto white balance calibration produces a colour curve for
    various colour temperatures, as well as providing a maximum 'wiggle room'
    distance from this curve (transverse_neg/pos).
    """
    def awb_cal(self, greyworld, do_alsc_colour):
        if 'rpi.awb' in self.disable:
            return 1
        print('\nStarting AWB calibration')
        self.log_new_sec('AWB')
        """
        if image is greyscale then AWB makes no sense
        """
        if self.grey:
            print('\nERROR: Can\'t do AWB on greyscale image!')
            self.log += '\nERROR: Cannot perform AWB calibration '
            self.log += 'on greyscale image!\nAWB aborted!'
            del self.json['rpi.awb']
            return 0
        """
        optional set greyworld (e.g. for noir cameras)
        """
        if greyworld:
            self.json['rpi.awb']['bayes'] = 0
            self.log += '\nGreyworld set'
        """
        Check if alsc tables have been generated, if not then do awb without
        alsc correction
        """
        if ("rpi.alsc" not in self.disable) and do_alsc_colour:
            try:
                cal_cr_list = self.json['rpi.alsc']['calibrations_Cr']
                cal_cb_list = self.json['rpi.alsc']['calibrations_Cb']
                self.log += '\nALSC tables found successfully'
            except KeyError:
                cal_cr_list, cal_cb_list = None, None
                print('ERROR, no ALSC calibrations found for AWB')
                print('Performing AWB without ALSC tables')
                self.log += '\nWARNING: No ALSC tables found.\nAWB calibration '
                self.log += 'performed without ALSC correction...'
        else:
            cal_cr_list, cal_cb_list = None, None
            self.log += '\nWARNING: No ALSC tables found.\nAWB calibration '
            self.log += 'performed without ALSC correction...'
        """
        call calibration function
        """
        plot = "rpi.awb" in self.plot
        awb_out = awb(self, cal_cr_list, cal_cb_list, plot)
        ct_curve, transverse_neg, transverse_pos = awb_out
        """
        write output to json
        """
        self.json['rpi.awb']['ct_curve'] = ct_curve
        self.json['rpi.awb']['sensitivity_r'] = 1.0
        self.json['rpi.awb']['sensitivity_b'] = 1.0
        self.json['rpi.awb']['transverse_pos'] = transverse_pos
        self.json['rpi.awb']['transverse_neg'] = transverse_neg
        self.log += '\nAWB calibration written to json file'
        print('Finished AWB calibration')

    """
    Auto lens shading correction completely mitigates the effects of lens shading for ech
    colour channel seperately, and then partially corrects for vignetting.
    The extent of the correction depends on the 'luminance_strength' parameter.
    """
    def alsc_cal(self, luminance_strength, do_alsc_colour):
        if 'rpi.alsc' in self.disable:
            return 1
        print('\nStarting ALSC calibration')
        self.log_new_sec('ALSC')
        """
        check if alsc images have been taken
        """
        if len(self.imgs_alsc) == 0:
            print('\nError:\nNo alsc calibration images found')
            self.log += '\nERROR: No ALSC calibration images found!'
            self.log += '\nALSC calibration aborted!'
            return 1
        self.json['rpi.alsc']['luminance_strength'] = luminance_strength
        if self.grey and do_alsc_colour:
            print('Greyscale camera so only luminance_lut calculated')
            do_alsc_colour = False
            self.log += '\nWARNING: ALSC colour correction cannot be done on '
            self.log += 'greyscale image!\nALSC colour corrections forced off!'
        """
        call calibration function
        """
        plot = "rpi.alsc" in self.plot
        alsc_out = alsc_all(self, do_alsc_colour, plot)
        cal_cr_list, cal_cb_list, luminance_lut, av_corn = alsc_out
        """
        write ouput to json and finish if not do_alsc_colour
        """
        if not do_alsc_colour:
            self.json['rpi.alsc']['luminance_lut'] = luminance_lut
            self.json['rpi.alsc']['n_iter'] = 0
            self.log += '\nALSC calibrations written to json file'
            self.log += '\nNo colour calibrations performed'
            print('Finished ALSC calibrations')
            return 1

        self.json['rpi.alsc']['calibrations_Cr'] = cal_cr_list
        self.json['rpi.alsc']['calibrations_Cb'] = cal_cb_list
        self.json['rpi.alsc']['luminance_lut'] = luminance_lut
        self.log += '\nALSC colour and luminance tables written to json file'

        """
        The sigmas determine the strength of the adaptive algorithm, that
        cleans up any lens shading that has slipped through the alsc. These are
        determined by measuring a 'worst-case' difference between two alsc tables
        that are adjacent in colour space. If, however, only one colour
        temperature has been provided, then this difference can not be computed
        as only one table is available.
        To determine the sigmas you would have to estimate the error of an alsc
        table with only the image it was taken on as a check. To avoid circularity,
        dfault exaggerated sigmas are used, which can result in too much alsc and
        is therefore not advised.
        In general, just take another alsc picture at another colour temperature!
        """

        if len(self.imgs_alsc) == 1:
            self.json['rpi.alsc']['sigma'] = 0.005
            self.json['rpi.alsc']['sigma_Cb'] = 0.005
            print('\nWarning:\nOnly one alsc calibration found'
                  '\nStandard sigmas used for adaptive algorithm.')
            print('Finished ALSC calibrations')