Mercurial > hg > orthanc-book
comparison Sphinx/source/plugins/python/pil-conversions.py @ 706:c62539d00251
Conversions between Orthanc and Python images
author | Sebastien Jodogne <s.jodogne@gmail.com> |
---|---|
date | Fri, 11 Jun 2021 12:42:39 +0200 |
parents | |
children | 8a247c645ac6 |
comparison
equal
deleted
inserted
replaced
705:745d93684b0b | 706:c62539d00251 |
---|---|
1 import json | |
2 import PIL.Image | |
3 import PIL.ImageDraw | |
4 import orthanc | |
5 | |
6 URL = 'http://hg.orthanc-server.com/orthanc-tests/raw-file/Orthanc-1.9.3/Database/LenaTwiceWithFragments.dcm' | |
7 USERNAME = '' | |
8 PASSWORD = '' | |
9 | |
10 def OnChange(changeType, level, resource): | |
11 if changeType == orthanc.ChangeType.ORTHANC_STARTED: | |
12 | |
13 # (1) Download a sample DICOM instance and decode it | |
14 orthanc.LogWarning('Downloading: %s' % URL) | |
15 lena = orthanc.HttpGet(URL, USERNAME, PASSWORD) | |
16 | |
17 dicom = orthanc.CreateDicomInstance(lena) | |
18 orthanc.LogWarning('Number of frames: %d' % dicom.GetInstanceFramesCount()) | |
19 | |
20 # (2) Access the first frame of the instance as a PIL image | |
21 frame = dicom.GetInstanceDecodedFrame(0) | |
22 size = (frame.GetImageWidth(), frame.GetImageHeight()) | |
23 | |
24 if frame.GetImagePixelFormat() == orthanc.PixelFormat.RGB24: | |
25 mode = 'RGB' | |
26 else: | |
27 raise Exception('Unsupported pixel format') | |
28 | |
29 image = PIL.Image.frombuffer(mode, size, frame.GetImageBuffer(), 'raw', mode, 0, 1) | |
30 | |
31 # (3) Draw a red cross over the PIL image | |
32 draw = PIL.ImageDraw.Draw(image) | |
33 draw.line((0, 0) + image.size, fill=(255,0,0), width=10) | |
34 draw.line((0, image.size[1], image.size[0], 0), fill=(255,0,0), width=10) | |
35 | |
36 # (4) Convert back the modified PIL image to an Orthanc image | |
37 buf = image.tobytes() | |
38 a = orthanc.CreateImageFromBuffer(frame.GetImagePixelFormat(), image.size[0], image.size[1], | |
39 len(buf) / image.size[1], buf) | |
40 | |
41 # (5) Create and upload a new DICOM instance with the modified frame | |
42 tags = { | |
43 'SOPClassUID' : '1.2.840.10008.5.1.4.1.1.1', | |
44 'PatientID' : 'HELLO', | |
45 'PatientName' : 'WORLD', | |
46 } | |
47 | |
48 s = orthanc.CreateDicom(json.dumps(tags), a, orthanc.CreateDicomFlags.GENERATE_IDENTIFIERS) | |
49 orthanc.RestApiPost('/instances', s) | |
50 orthanc.LogWarning('Image successfully modified and uploaded!') | |
51 | |
52 orthanc.RegisterOnChangeCallback(OnChange) |