1

To start things of. I'm new to the image workflow of Python. But I am fairly good at python overall. But i can't seem to find a good solution for displaying RAW .NEF files from a Nikon camera in python. What i want to do is to open the RAW file, convert it to QImage or QPixmap and then display it without saving the image. I have tried libraries such as PIL, rawpy and numpy. But i heard that there is usually an embedded JPEG in the raw files. Is there a neat way to extract that? From what i've found on the internet, people convert the raw file and then save it as a jpeg. But I need to show it without saving it.

with rawpy.imread(file) as raw:
    rgb = raw.postprocess()
rgb = np.transpose(rgb, (1, 0, 2)).copy()
h, w, a = rgb.shape
qim = QtGui.QImage(rgb, w, h, QtGui.QImage.Format_RGB888)

This is what i've been trying now. But that returns None.

fd = file(file_path, 'rb')
# Skip over header + directory
# See manufacture specification
offset = 16  # Magic bytes
offset += 12  # Version
offset += 32  # Camera name
offset += 24  # Directory start & meta
fd.seek(offset, 0)
jpeg_offset = unpack('i', fd.read(4))  # Read where JPEG data starts
jpeg_length = unpack('i', fd.read(4))  # Read size of JPEG data
fd.seek(jpeg_offset[0], 0)
jpg_blob = fd.read(jpeg_length[0])
im = QtGui.QImage(jpg_blob)

This is what i tried to extract the embedded JPEG. But that also return None.

Thank you in advance.

ziarra
  • 21
  • 3

1 Answers1

0

Using my old answer to convert the numpy image to QImage.

import os
import sys
import rawpy
from PySide import QtCore, QtGui


def read_nef(path):
    image = QtGui.QImage()
    with rawpy.imread(path) as raw:
        src = raw.postprocess()
        h, w, ch = src.shape
        bytesPerLine = ch * w
        buf = src.data.tobytes() # or bytes(src.data)
        image = QtGui.QImage(buf, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
    return image.copy()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    w = QtGui.QLabel(scaledContents=True)
    w.resize(640, 480)
    w.show()

    current_dir = os.path.dirname(os.path.realpath(__file__))

    # http://www.luminescentphoto.com/nx2/nefs.html
    filepath = os.path.join(current_dir, "baby.nef")
    image = read_nef(filepath)

    w.setPixmap(QtGui.QPixmap.fromImage(image))
    sys.exit(app.exec_())

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Im getting an error while trying this code. `buf = src.data.tobytes() AttributeError: 'buffer' object has no attribute 'tobytes'`. – ziarra Sep 20 '19 at 08:05
  • 1
    Got it to work with a suggestion you had in your old answer. I changed the src.data.tobytes() to bytes(src.data). – ziarra Sep 20 '19 at 08:10