Skip to content

Instantly share code, notes, and snippets.

@sriharijayaram5
Created June 10, 2021 15:37
Show Gist options
  • Save sriharijayaram5/7e5b4ac33646aa18aef9d1213bfd6bf5 to your computer and use it in GitHub Desktop.
Save sriharijayaram5/7e5b4ac33646aa18aef9d1213bfd6bf5 to your computer and use it in GitHub Desktop.
SLM display images from folder
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os, sys, time\n",
"\n",
"# Import the SLM Display SDK:\n",
"import SLM_Examples.detect_heds_module_path\n",
"from holoeye import slmdisplaysdk\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from PIL import Image\n",
"import datetime\n",
"\n",
"# Make some enumerations available locally to avoid too much code:\n",
"ErrorCode = slmdisplaysdk.SLMDisplay.ErrorCode\n",
"ShowFlags = slmdisplaysdk.SLMDisplay.ShowFlags\n",
"State = slmdisplaysdk.SLMDisplay.State\n",
"ApplyDataHandleValue = slmdisplaysdk.SLMDisplay.ApplyDataHandleValue\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def click_1(exp, n):\n",
" las_patt = [(55e6,0), (exp,1), (25e6,0)]\n",
" cam_patt = [(55e6,1), (exp,1), (25e6,0)]\n",
"\n",
" pulsestreamer._seq = pulsestreamer.pulse_streamer.createSequence()\n",
" pulsestreamer._seq.setDigital(0, las_patt)\n",
" pulsestreamer._seq.setDigital(1, cam_patt)\n",
" mycamera.ready_pulsed(n)\n",
" pulsestreamer.pulser_on()\n",
"\n",
"def click_2(n):\n",
" mycamlogic.start_trigger_seq(n)\n",
"\n",
"def click_3():\n",
" pulsestreamer.pulser_off()\n",
" mycamera.pulsed_done()\n",
" pulsestreamer.clear_all()\n",
"# pulsedmasterlogic.clear_pulse_generator()\n",
" pulsestreamer.pulser_on(laser=True)\n",
" return mycamlogic.get_last_image()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# # Configure slideshow:\n",
"# thisScriptPath = os.path.dirname(__file__)\n",
"# imageFolder = os.path.join(thisScriptPath, \"data\", \"vertical_grating\")\n",
"# 14_05_2021\\20210514-1037-03\n",
"imageFolder = 'C:/Data/SLM_Patterns/05_05_2021/20210505-1819-10'\n",
"imageDisplayDurationMilliSec = 500 # please select the duration in ms each image file shall be shown on the SLM\n",
"repeatSlideshow = 1 # <= 0 (e. g. -1) repeats until Python process gets killed\n",
"\n",
"# Initializes the SLM library\n",
"slm = slmdisplaysdk.SLMDisplay()\n",
"\n",
"# Check if the library implements the required version\n",
"if not slm.requiresVersion(2):\n",
" exit(1)\n",
"\n",
"# Detect SLMs and open a window on the selected SLM\n",
"error = slm.open()\n",
"assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
"# Open the SLM preview window in non-scaled mode:\n",
"# This might have an impact on performance, especially in \"Capture SLM screen\" mode.\n",
"# Please adapt the file showSLMPreview.py if preview window is not at the right position or even not visible.\n",
"from SLM_Examples.showSLMPreview import showSLMPreview\n",
"showSLMPreview(slm, scale=1.0)\n",
"\n",
"# Please select how to scale and transform image files while displaying:\n",
"displayOptions = ShowFlags.PresentAutomatic # PresentAutomatic == 0 (default)\n",
"#displayOptions |= ShowFlags.TransposeData\n",
"#displayOptions |= ShowFlags.PresentTiledCentered # This makes much sense for holographic images\n",
"#displayOptions |= ShowFlags.PresentFitWithBars\n",
"#displayOptions |= ShowFlags.PresentFitNoBars\n",
"#displayOptions |= ShowFlags.PresentFitScreen\n",
"\n",
"# Search image files in given folder:\n",
"filesList = os.listdir(imageFolder)\n",
"\n",
"# Filter *.png, *.bmp, *.gif, and *.jpg files:\n",
"imagesList = [filename for filename in filesList if str(filename).endswith(\".png\") or str(filename).endswith(\".gif\") or str(filename).endswith(\".bmp\") or str(filename).endswith(\".jpg\")]\n",
"\n",
"imagesList.sort()\n",
"\n",
"print(imagesList)\n",
"\n",
"print(\"Number of images found in imageFolder = \" + str(len(imagesList)))\n",
"\n",
"if len(imagesList) <= 0:\n",
" sys.exit()\n",
"\n",
"\n",
"# Upload image data to GPU:\n",
"print(\"Loading data ...\")\n",
"start_time = time.time()\n",
"\n",
"durationInFrames = int((float(imageDisplayDurationMilliSec)/1000.0) * slm.refreshrate_hz)\n",
"if durationInFrames <= 0:\n",
" durationInFrames = 1 # The minimum duration is one video frame of the SLM\n",
"\n",
"print(\"slm.refreshrate_hz = \" + str(slm.refreshrate_hz))\n",
"print(\"durationInFrames = \" + str(durationInFrames))\n",
"\n",
"dataHandles = []\n",
"\n",
"nHandle = 0 # total number of images loaded to GPU\n",
"for filename in imagesList:\n",
" filepath = os.path.join(imageFolder, filename)\n",
"\n",
" # Load image data to GPU:\n",
" error, handle = slm.loadDataFromFile(filepath)\n",
" assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
" error = slm.datahandleWaitFor(handle, State.LoadingFile)\n",
" assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
" handle.durationInFrames = durationInFrames\n",
"\n",
" error = slm.datahandleApplyValues(handle, ApplyDataHandleValue.DurationInFrames)\n",
" assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
" # Wait for actual upload of image data to GPU:\n",
" slm.datahandleWaitFor(handle, State.ReadyToRender)\n",
"\n",
" nHandle += 1\n",
" dataHandles.append(handle)\n",
"\n",
"print(\"100%\")\n",
"end_time = time.time()\n",
"print(\"Loading files took \"+ str(\"%0.3f\" % (end_time - start_time)) +\" seconds\\n\")\n",
"\n",
"# Play complete slideshow:\n",
"n = 0\n",
"imgs0 = []\n",
"while (n < repeatSlideshow) or (repeatSlideshow <= 0):\n",
" n += 1\n",
" print(\"Show images for the \" + str(n) + \". time ...\")\n",
"\n",
" # Play slideshow once:\n",
" for i, handle in enumerate(dataHandles):\n",
" click_1((imageDisplayDurationMilliSec - 50)*1e6, 1)\n",
" error = slm.showDatahandle(handle, displayOptions)\n",
" click_2(1)\n",
" imgs0.append(click_3())\n",
" assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
" # Update the handles to the latest state:\n",
" for handle in dataHandles:\n",
" error = slm.updateDatahandle(handle)\n",
"\n",
"# One last image to clear the SLM screen after the slideshow playback:\n",
"# (Also possible by just calling slm.showBlankscreen(128))\n",
"data = slmdisplaysdk.createFieldUChar(1, 1)\n",
"\n",
"if slmdisplaysdk.supportNumPy:\n",
" data[0, 0] = 128\n",
"else:\n",
" data[0][0] = 128\n",
"\n",
"error, dh = slm.loadData(data)\n",
"assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
"error = slm.showDatahandle(dh, ShowFlags.PresentAutomatic)\n",
"assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
"# Release handles and their data to free up video memory:\n",
"dataHandles = None\n",
"\n",
"# # Wait until the SLM process is closed:\n",
"error = slm.utilsWaitUntilClosed()\n",
"assert error == ErrorCode.NoError, slm.errorString(error)\n",
"\n",
"# Unloading the SDK may or may not be required depending on your IDE:\n",
"slm = None\n",
"imgs = np.asarray(imgs0)[:,0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"for i in range(9):\n",
" plt.figure(figsize=(9,9))\n",
" plt.imshow(imgs[i], cmap='inferno')\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"image_list = []\n",
"timestamp = datetime.datetime.now()\n",
"t = timestamp.strftime(\"%Y%m%d-%H%M-%S\")\n",
"for image in imgs :\n",
" image_list.append(Image.fromarray(image.astype('float')))\n",
"maxmin = Image.fromarray(np.max(imgs, axis=0) - np.min(imgs, axis=0).astype('float'))\n",
"av = Image.fromarray(np.mean(imgs, axis=0).astype('float'))\n",
"# image_list.append(maxmin)\n",
"# image_list.append(av)\n",
"image_list[0].save(f\"{imageFolder}/Results/{t}_{imageDisplayDurationMilliSec}ms.tif\", save_all=True, append_images=image_list[1:])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.imshow(np.max(imgs, axis=0) - np.min(imgs, axis=0))\n",
"plt.show()\n",
"print(imgs.shape)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Qudi",
"language": "python",
"name": "qudi"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": "3.6.5"
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment