Giter Club home page Giter Club logo

luxpy's Introduction

Python toolbox for lighting and color science

  • Author: Kevin A.G. Smet (ksmet1977 at gmail.com)
  • Version: 1.10.1
  • Date: November 24, 2023
  • License: GPLv3

DOI

Cite LuxPy:

If you use the package, please cite the following tutorial paper published in LEUKOS: Smet, K. A. G. (2020). Tutorial: The LuxPy Python Toolbox for Lighting and Color Science. LEUKOS, 1–23. DOI: 10.1080/15502724.2018.1518717

NEW luxpy basic web-app [under development]:

For some online spectral calculations (ANSI/IES TM30, CIE 13.3-1995 Ra, CIE 224:2017 Rf, alpha-opic irradiances, Equivalent Daylight Illuminance (EDI), Efficacy of Luminous Radiation (ELR), Daylight Efficacy Ratio (DER), IES/LDT Luminous Intensity Distribution plots/renders, ...) using a python web-application: luxpy.herokuapp.com or share.streamlit.io/ksmet1977/luxpy_app/main/luxpy_app.py


What is LuxPy?

Luxpy is an open source package under a GPLv3 license that supports several common lighting, colorimetric, color appearance and other color science related calculations and models, such as:

  • spectral data interpolation (conform CIE15-2018) and normalization
  • calculation of daylight phase, blackbody radiator and other reference illuminant spectra
  • calculation of tristimulus values
  • correlated color temperature and Duv (methods: robertson1968/2022, ohno2014, li2016, zhang2019, li2022)
  • color space transformations
  • chromatic adaptation transforms
  • color appearance models
  • color rendition indices (eg. CIE Ra, CIE 224:2017 Rf, ANSI/IES TM30 Rf, Rg, ... + IES TM30 Annex E priority levels & reports)
  • calculation of photobiological quantities (eg melanopic irradiance, MEDI, CS, ...)
  • multi-component spectrum creation and optimization
  • hyper-spectral image simulation and rendering
  • MacAdam ellipses
  • color differences (cam02ucs, DE2000, ...)
  • modelling of individual observer color matching functions (Asano, 2016)
  • calculation of CIEOP06 (cfr. CIE TC1-97) color matching functions and cone-fundamentals
  • display characterization
  • reading and visualizing IES and LDT photometric files (vizualizations: 2D polar plots, 3D plots, single-bounce physical-based rendering)
  • spectral mismatch (f1', correction factors) and measurement uncertainty (under development)
  • Basic TechnoTeam LMK (LabSoft) control: do XYZ-map and Y-map measurements
  • Virtual Reality Head-Mounted-Display viewer for stereoscopic (equirectangular) images using Harfang Python framework
  • ...

As of May 2019, LuxPy now also has a toolbox spectro for spectral measurements with JETI and OceanOptics spectrometers:

  • spectro.jeti: easy installation (dll's are part of sub-package).
  • spectro.oceanoptics: more tricky installation (requires manual install of python-seabreeze, ...; see here or subpackage help for more info)

UPDATED (May, 2021): ANSI/IES-TM30-2018 graphical output (Color Rendition Reports, Color Vector Graphics, Annex E priority levels...)


How to use LuxPy (basics)?

Luxpy can be easily installed from pypi pip install luxpy or anaconda conda install -c ksmet1977 luxpy.

An overview of the basic usage is given in the luxpy basic usage.ipynb jupyter notebook (!! Don't right-click to save, see below for download instructions !!), as well as the tutorial paper published in LEUKOS: Smet, K. A. G. (2020). Tutorial: The LuxPy Python Toolbox for Lighting and Color Science. LEUKOS, 1–23. DOI: 10.1080/15502724.2018.1518717

  • !!! To download jupyter notebook:
    1. Open the notebook in github by clicking it and then press download button at the top right; don't right-click the notebook link itself and use 'save as ...', as this apparently results in some NotJSONError when opening the notebook!
    2. If the jupyter notebook fails to open or download or still gives an error: (Github seems to experience some type of problem sometimes with its jupyter notebook backend, see issue), try opening the file using the nbviewer.jupyter.org online viewer, (or just click this direct link: nbviewer.jupyter.org/github/ksmet1977/luxpy/blob/master/luxpy_basic_usage.ipynb) and then download it from there (use download notebook button at the top right of the page).

For more details on structure, functionality, etc., see:

  1. the github pages on: ksmet1977.github.io/luxpy/

  2. the LuxPy_Documentation pdf

  3. or, the __doc__string of each function.

    To get help on, for example the spd_to_xyz() function, type:

        import luxpy as lx
        ?lx.spd_to_xyz
    

    To get a list of functions/modules, type:

        dir(lx)
    

Python tutorials

Some basic tutorials can be found at:

A list of basic and more advanced is given at:

Matlab versus Python:

Udemy.com:

  • Udemy.com offers some great courses. Although some of these are payed, they often come at huge discounted prices.

Youtube.com:

luxpy's People

Contributors

klabautergans avatar ksmet1977 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

luxpy's Issues

SPD dataset - Light sources database

Hi Kevin,

Thanks for the great library. This is not an issue, but I don't know where to ask it since this repo does not have a discussion forum.
I see in Luxpy we have spectral database, or in some places, I see you are dealing with excel files to get spectral data.
But where can I download those excel files and use it for my research works?
Is there any good SPD dataset with the corresponding published papers?

Thanks

Error in xyz_to_cct_search_fast

Dear,

I am working on an optimisation project related to spectral distributions and different constraints. One of the constraints includes the TM-30 fidelity index (spd_to_cri method), but after a while LuxPy raises an error message in the xyz_to_cct_search_fast method. I'm not sure why this is happening, or whether this is a bug of some sort. I have included a screenshot so you have an idea what exactly is the error. What could cause this?

Thanks.
error

Reduce required dependencies?

I'm looking for a small package that can convert from RGB to CAM16UCS (and also Oklab and Srlab2, but they are easy to implement).

  • Colorio fits the bill, but it is closed sourced and obfuscated.
  • color-science can do conversions, but is a gigantic bloated package.
  • colorspacious is nice and light, but it doesn't support Cam16UCS
  • luxpy can do the conversions and it is light, but has gigantic bloated dependencies.

Would you be willing to reduce the required dependencies? This would mean removing these dependencies "requires", and ensuring that code still can run without them:

  • remove scipy
  • remove matplotlib
  • remove pandas
  • imageio (possibly)

These dependencies could still be part of requirements.txt (for testing and build time), and to support optional functionality. The could also be added to the "extra_requires" section of the package.

Looking briefly at the code, it appears that none of these dependencies are required for the core logic of luxypy. It is possible that the places they are used could be changed into lazy imports inside of functions instead of at the top of a file, and this would be enough to make luxpy useful without downloading the larger libraries.

What do you think?

Illuminance E [lx] from spectral data

I know the question is quite trivial, but which luxpy subpackage should I use to calculate illuminance in lx starting from spectral data in W⋅m−2⋅nm−1?

np.float is deprecated

using newest numpy (1.24.2) with luxpy 1.9.8, both installed via pip, leads to an error using the spd_to_cri() function. In fact, np.float is apparently deprecated and that might lead to more issues. A grep search finds at least seven files using np.float.

luxpy problems after Azure Function deployment

Hi, I'm trying to use luxpy package to unload IES data for further calculations. Locally package works prefect, but after deploying to Azure Function using read_lamp_data() function causes errors. Worth to mention that after adding import luxpy I had problems to even succesfully deploy code to functions. Only moving import luxpy to function that uses it solves that problem. After all, I think it helped to add all the packages mentioned in the pdf instructions to a requirements.txt file. Function deploys, but doesn't work :( I've tried both 3.10 and 3.11 versions of Azure Function. My colleague had similar problems with deploying it to AWS Labda.

My python code takes link to EIS file given in request body, downloads it, load from file and use for further calculations. Problematic part looks like this:

logging.info(f'Loading IES file...')
ies = load_ies_from_bytes(ies_data)
if(ies == None):
    raise Exception(f"Failed to load IES file. Update input request body.")
logging.info(f'Succesfully loaded IES file.')

it uses custom load_ies_from_bytes() function:

def load_ies_from_bytes(ies_data):
    '''Function that loads IES file from bytes'''
    try:
        import luxpy as lx
        ies = lx.toolboxes.iolidfiles.read_lamp_data(ies_data)
        return ies
    except Exception as e:
        print(f"[Inside Load IES] Error loading IES file: {e}")
        for args in e.args:
            print(args)
        return None

After sending request to my function with valid link to IES file, logs looks like this:

2024-05-22T10:46:43Z   [Information]   Downloading IES file...
2024-05-22T10:46:44Z   [Information]   Succesfully downloaded IES file.
2024-05-22T10:46:44Z   [Information]   Loading IES file...
2024-05-22T10:46:48Z   [Information]   generated new fontManager
2024-05-22T10:47:05Z   [Warning]   /home/site/wwwroot/.python_packages/lib/site-packages/luxpy/color/cct/cct_legacy.py:624: SyntaxWarning: "is" with a literal. Did you mean "=="?
2024-05-22T10:47:05Z   [Information]     if (cct_search_list is None) or (cct_search_list is 'default'):
2024-05-22T10:47:05Z   [Warning]   /home/site/wwwroot/.python_packages/lib/site-packages/luxpy/color/cct/cct_legacy.py:625: SyntaxWarning: "is not" with a literal. Did you mean "!="?
2024-05-22T10:47:05Z   [Information]     if (cct_search_list_default is None) or (cct_search_list is not 'default'):
2024-05-22T10:47:05Z   [Information]   [Inside Load IES] Error loading IES file: [Errno 30] Read-only file system: '/home/site/wwwroot/.python_packages/lib/site-packages/luxpy/data/cctluts/legacy/cct_lut_cctlist_robertson1968.dat'
2024-05-22T10:47:05Z   [Information]   30
2024-05-22T10:47:05Z   [Information]   Read-only file system
2024-05-22T10:47:05Z   [Error]   Failed to load IES file. Update input request body.
2024-05-22T10:47:05Z   [Information]   Executed 'Functions.cu_calculations' (Succeeded, Id=24cb8b41-f5be-4df4-8024-0dcf96ca7098, Duration=22689ms)

That's not only error I got. I also had things like NameError: name 'spectrum' is not defined or NameError: name 'lp' is not defined. Despite the fact that I do not have such things in my code, so I suspect thats related to luxpy package.

Only task of this function is to decode the ies file and send it on. I've tried ensure to install all packages I've found here, so my requirements.txt looks like this:

azure-functions
scipy
scikit-learn
numpy
pandas
matplotlib
setuptools
imageio
git+https://github.com/ksmet1977/luxpy.git#egg=luxpy

Once again, locally it works perfect, but after deploy to cloud it can't execute. I've tried installing luxpy from this repo (instead of pypi), also ensured to add all packages to requirements.txt. Nothing works.

Any ideas how to deal with it?

edit:
I've temporarly delt with [Errno 30] Read-only file system: '/home/site/wwwroot/.python_packages/lib/site-packages/luxpy/data/cctluts/legacy/cct_lut_cctlist_robertson1968.dat' error by adding Azure configuration setting: "FUNCTION_APP_EDIT_MODE": "readwrite" as showed here: https://learn-attachment.microsoft.com/api/attachments/240163-image.png?platform=QnA

Now I have new errors. Logs:

2024-05-22T12:02:16Z   [Information]   Downloading IES file...
2024-05-22T12:02:16Z   [Information]   Succesfully downloaded IES file.
2024-05-22T12:02:16Z   [Information]   Loading IES file...
2024-05-22T12:02:16Z   [Error]   Failed to load IES file. Update input request body.
2024-05-22T12:02:16Z   [Information]   [Inside Load IES] Error loading IES file: name 'spectrum' is not defined
2024-05-22T12:02:16Z   [Information]   name 'spectrum' is not defined

and also:

2024-05-22T12:18:21Z   [Information]   [Inside Load IES] Error loading IES file: module 'luxpy' has no attribute 'toolboxes'
2024-05-22T12:18:21Z   [Information]   module 'luxpy' has no attribute 'toolboxes'

There is no info where this error occurs in luxpy package. Any ideas how to deal with it?

Thank you in advance,
Karol

reference to xyz_to_duv missing in cct.py

Noticed that after recent commit, xyz_to_duv is missing from __all__ in cct.py. Other references may be missing, too?


Great package! Thanks for putting this together and maintaining it!

Rendering Error in hyper-spectral images Module

I am unable to reproduce the rendered image from the example given in section 4.4 of the documentation article, using the same sample image.

The example code I ran:

import luxpy
from luxpy import hypspcim
import luxpy.toolboxes.spdbuild as spb 

S = spb.spd_builder(peakwl = [450,530,610],
                  fwhm = [10,10,10],
                  target = 4000,
                  tar_type = 'cct')

img_hyp = hypspcim.render_image(img = 'testimage1.jpg',
                                cspace = 'ipt',
                                spd = S,
                                D = 1,
                                show = True,
                                stack_test_ref = 21)

gives me this image.

Low CCT

Hello,

I am trying to calculate the circadian-related parameters (CS and CLa, basically) of a given spd and I have noticed that there is an important difference between the luxpy results and the "official" LRC webpage (https://www.lrc.rpi.edu/cscalculator/) results for low CCTs. I suppose that this error is not directly related with the CCT, but the LRC functions have a discontinuity and the circadian sensitivity curve changes at some point (around 3300 K). This behavior can be seen graphically at the webpage of the LRC. I have seen the provided luxpy documentation and there are some comments related with the calculation of these parameters, but I don't know if that issue could be solved in a simple way.

Thank you for creating/maintaining this awesome library.

setup.py error

  1. The os and warnings should be removed from the "install_requires" list
  2. The line "version = '0.6'," does not match the declared version (0.7)

Converting RGB to spectrum and back to RGB

I have an RGB image and I want to simulate the effects of a chromatic filter over it. Namely, I wrote a function that converts RGB to spectral data, performs the filtering, and then comes back to RGB. The problem is that even when I skip the filtering step, the input and output images are extremely different. I don't know if this is an expected behaviour, if I'm doing something wrong or if there's a bug in the library.

Here's a toy example to show what I mean:

import numpy as np
import luxpy as lx
import matplotlib.pyplot as plt
import cv2

def filter_img(rgb_img, lambda_min, lambda_max):
    # Store the actual shape of the image
    original_shape = rgb_img.shape

    # Calculate the spectrum for each pixel in the image
    spectral_data = lx.toolboxes.rgb2spec.convert(rgb_img.reshape(-1, 3), intent="spd")
    lambdas, spectra = spectral_data[0], spectral_data[1:]

    # Filter the desired wavelengths here: set to 0 the undesired spectral components
    filter_mask = (lambdas >= lambda_min) & (lambdas <= lambda_max)
    filtered_spectra = np.multiply(spectra, filter_mask.T)

    # Calculate the XYZ values with the (filtered) spectral information
    filtered_xyz = (lx.spectrum.spd_to_xyz(np.vstack([lambdas, filtered_spectra]), relative=True)
                    .reshape(original_shape))
    
    # Do the correct normalization so that OpenCV can understand the XYZ values
    filtered_xyz = (np.nan_to_num(filtered_xyz) * 255 / 100).astype("uint8")
    
    # Convert back to RGB
    filtered_rgb = cv2.cvtColor(filtered_xyz, cv2.COLOR_XYZ2RGB)
    
    return filtered_rgb

original_img = np.array([[[255, 0, 0], [0, 255, 0]],
                         [[0, 0, 255], [255, 255, 0]],
                         [[0, 0, 0], [255, 255, 255]],
                         [[0, 255, 255], [255, 0, 255]]]).swapaxes(0, 1)

# Use 0 and 900 so that no wavelengths are filtered
filtered_img = filter_img(original_img, 0, 900)

f, axes = plt.subplots(1, 2)
axes[0].imshow(original_img , origin='upper')
axes[1].imshow(filtered_img , origin='upper')

On the left we can see the original image, and on the right the output (they should be the same as far as I understand):

imgs

Am I doing something wrong? Is the algorithm supposed to work like this?

Can't open user-provided IES files

Hi,
I'm trying to use luxpy to read photometric data from a .ies file into an array. However, I can't seem to get it to open the file from a file path correctly.

I import modules like so:

import luxpy as lx
from luxpy import iolidfiles as iolid
from io import StringIO

Our .ies file path (placed the file in the iolid data directory as I thought this could be the problem):

typeB_20deg_filepath = iolid._PATH_DATA + 'TypeB_20degBeam.ies'

I've apparently tried all three ways of ingesting .ies data in using the read_lamp_data function, with varying errors:

Using this raw text path:

LID_typeB_20deg = iolid.read_lamp_data(typeB_20deg_filepath, verbosity=1)

yields:
image

Using a StringIO object:

typeB_20deg_path_stringio = StringIO(typeB_20deg_filepath)
LID_typeB_20deg = iolid.read_lamp_data(typeB_20deg_path_stringio, verbosity=1)

yields:
image

And using the raw text from the file:

typeB_20deg_string = ""
with open(typeB_20deg_filepath, 'r') as f:
    typeB_20deg_string = f.read()
LID_typeB_20deg = iolid.read_lamp_data(typeB_20deg_string, verbosity=1)

yields:
image

Using one of the given examples in the iolid data directory:

LID_path = iolid._PATH_DATA + 'luxpy_test_lid_file.ies'

And checking various parameters yields no major inconsistencies between the two file paths:
image

Any guidance would be appreciated.

ImportError: cannot import name 'jab_to_rg'

Not sure if that's and issue with my dependencies or the luxpy package itself. However, I get above error with version > 1.6 (1.6.0 and 1.6.1) Versions up to 1.5.3 work fine. Installed in Thonny with it's own packaging system.

deprecation issue in numpy float

I am using Python 3.11.3 with numpy==1.25.1

import luxpy as lx
Rf = lx.cri.spd_to_cri(...)

The spd_to_cri function uses 'np.float' which is deprecated and aliases have been removed since Numpy ver 1.20. The error occurs in the function...
_get_hue_bin_data
inside the file...
luxpy/color/cri/utils/helpers.py.
inside the command...
wr = np.nansum(cndr_hj,axis=0,keepdims=True).astype(np.float)

The returned error is...
module 'numpy' has no attribute 'float'
and basically tells you to just use 'float' instead of 'np.float.'

I'd fix this myself but I am not a trained coder and am more comfortable with you looking into it.
-Jim

LuxPy and EML calculation

Hello. Thanks for sharing this fantastic toolbox.
This toolbox allows the calculation of MEDI to be performed. But, what about Equivalent Melanopic Lux (EML?) How can be calculated? Is there available an example?

rgb to multiple level color name mapping?

I am seeking a python multi-level rgb to colorname mapping module.

rgb2name((r,g,b), level)
level 0 might be 8 or 16 basic color names. (e.g. green)
level 1 might have 32 to 64 color names. (e.g. dark green, green, light green)
level 2 might have 64 to 256 color names. (more variants)

Is anything like this available?

Thank you.

UnboundLocalError: local variable 'dotAB' referenced before assignment

Forgive me if I'm doing something stupid ...

The following code produces the following error in basics.py dot23

import luxpy as lx
import numpy as np

data = np.array([185, 206, 163])
Rw = np.array([256, 264, 202])

camout = lx.cam.zcam(data, Rw)
UnboundLocalError: local variable 'dotAB' referenced before assignment
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-599aff8f528b> in <module>
      2 Rw = np.array([256, 264, 202])
      3 
----> 4 camout = lx.cam.zcam(data, Rw)

/usr/local/Caskroom/miniconda/base/lib/python3.8/site-packages/luxpy/color/cam/zcam.py in run(data, xyzw, outin, cieobs, conditions, forward, mcat, **kwargs)
    377     #--------------------------------------------
    378     # Apply CAT to white point:
--> 379     xyzwc = cat.apply_vonkries1(xyzw, xyzw1 = xyzw, xyzw2 = xyzw_d65, 
    380                                 D = D, mcat = mcat, invmcat = invmcat,
    381                                 use_Yw = True)

/usr/local/Caskroom/miniconda/base/lib/python3.8/site-packages/luxpy/color/cat/chromaticadaptation.py in apply_vonkries1(xyz, xyzw1, xyzw2, D, mcat, invmcat, in_, out_, use_Yw)
    671     # transform from xyz to cat sensor space:
    672     if in_ == 'xyz':
--> 673         rgb = math.dot23(mcat, xyz.T)
    674         rgbw1 = math.dot23(mcat, xyzw1.T)
    675         rgbw2 = math.dot23(mcat, xyzw2.T)

/usr/local/Caskroom/miniconda/base/lib/python3.8/site-packages/luxpy/math/basics.py in dot23(A, B, keepdims)
    235             dotAB = np.expand_dims(dotAB,axis=1)
    236 
--> 237     return dotAB
    238 
    239 #------------------------------------------------------------------------------

UnboundLocalError: local variable 'dotAB' referenced before assignment

OpenCV now a required dependency

I see that cv2 is now a required dependency in the latest version of luxpy. To date, luxpy has been wonderfully lean, and the dependencies have all been pretty standard for scientific computing users. But OpenCV is something different, it's big, hairy, slow to import, and difficult to install on many architectures.

Any chance that OpenCV could be removed as a requirement, and it's import done locally only in whichever function or module requires it?

I'm happy to provide a PR if this is a direction you're willing to go.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.