[Python] How do I use the python support in DigitalMicrograph to save a color image as PNG file

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I can use the python functionality to save a DM image into PNG, as long as it is NOT RGB data type. Here is the code for doing so:

    import tkinter as tk
    from tkinter import filedialog
    from skimage import io, img_as_ubyte, img_as_uint
    import numpy as np
    import DigitalMicrograph as DM

    # Hide the main window
    root = tk.Tk()
    root.withdraw()

    # Get DM image
    img = DM.GetFrontImage()
    img_data = img.GetNumArray()

    # Ask for save-path
    save_path = filedialog.asksaveasfilename(
    title='Save PNG image',
    defaultextension='.png',
    filetypes=[('PNG images', '*.png')],
    )

    if save_path:
    try:
    # Convert to uint8 (0–255) before saving
    img_u8 = img_as_ubyte(img_data)
    io.imsave(save_path, img_u8)
    print(f'Image saved to: {save_path}')
    except OSError as e:
    print(f'Failed to save image: {e}')
    else:
    print('Save canceled by user.')


    The script will fail if the front image is of RGB data type. I believe that the reason is the Py_image class does not support the GetNumArray() method. Is there a solution to this other than taking in 3 DM images (as red, green, blue channels)?

    Continue reading...

Compartilhe esta Página