-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpydicomsend.py
More file actions
192 lines (151 loc) · 7.54 KB
/
Copy pathpydicomsend.py
File metadata and controls
192 lines (151 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python
# coding: utf-8
# In[28]:
# Coded version of DICOM file 'app11he.dcm'
# Produced by pydicom codify utility script
import pydicom
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.sequence import Sequence
from PIL import Image
import numpy as np
import glob
from datetime import datetime
import random
import xmltodict
from pynetdicom import AE, debug_logger, StoragePresentationContexts
from pynetdicom.sop_class import CTImageStorage
import io
from pydicom.encaps import encapsulate
import requests
import psycopg2
file = open("allImageMetadata.xml", "r")
xml = file.read()
#Establishing the connection
conn = psycopg2.connect(
database="postgres", user='postgres', password='postgres', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
cursor = conn.cursor()
metadata = xmltodict.parse(xml)
# pynetdicom stuff
#debug_logger()
# Initialise the Application Entity
ae = AE()
# Add a requested presentation context
ae.requested_contexts = StoragePresentationContexts
# Associate with peer AE at IP 127.0.0.1 and port 104
assoc = ae.associate("127.0.0.1", 104)
if assoc.is_established:
for img in metadata['HistoImages']['image']:
# Read JPG and convert to Byte Array
jpg_image = Image.open(img['@src'])
description = img['description'].replace(" ", "^")
# Create unique SOPInstanceUID
now = datetime.now()
SOPInstanceUID = "1.2.826.10.1.3680043.8.654.10.2010." + now.strftime("X%d.X%m.X%Y.X%H.X%M.X%S").replace('X0','X').replace('X','') + "." + str(random.randint(1, 999999))
print(SOPInstanceUID)
# direkt mit DICOM Send an Server
# File meta info data elements
file_meta = FileMetaDataset()
file_meta.FileMetaInformationGroupLength = 178
file_meta.FileMetaInformationVersion = b'\x00\x01'
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.7'
file_meta.MediaStorageSOPInstanceUID = SOPInstanceUID
file_meta.TransferSyntaxUID = '1.2.840.10008.1.2'
file_meta.ImplementationClassUID = '1.2.40.0.13.1.1'
file_meta.ImplementationVersionName = 'dcm4che-2.0'
# Main data elements
ds = Dataset()
ds.SpecificCharacterSet = 'ISO_IR 100'
ds.InstanceCreationDate = '20100303'
ds.InstanceCreationTime = '152750.242'
ds.SOPClassUID = '1.2.840.10008.5.1.4.1.1.7'
ds.SOPInstanceUID = SOPInstanceUID
ds.StudyDate = '20100303'
ds.StudyTime = '1815'
ds.AccessionNumber = ''
ds.Modality = 'OT'
ds.ConversionType = 'SI'
ds.Manufacturer = ''
ds.ReferringPhysicianName = 'House^Gregory'
ds.StudyDescription = 'Duennschnittstudien'
ds.PatientName = 'Telvis^Test'
ds.PatientID = '424243'
ds.PatientBirthDate = '19700101'
ds.PatientSex = 'M'
ds.StudyInstanceUID = '1.2.826.0.1.3680043.8.654.10.2010'
ds.SeriesInstanceUID = '1.2.826.0.1.3680043.8.654.20.2010'
ds.StudyID = '0000100'
ds.SeriesNumber = '1'
ds.InstanceNumber = '1'
ds.ImageComments = description
ds.SamplesPerPixel = 3
ds.PhotometricInterpretation = 'RGB'
ds.PlanarConfiguration = 0
ds.Rows = jpg_image.height
ds.Columns = jpg_image.width
ds.BitsAllocated = 8
ds.BitsStored = 8
ds.HighBit = 7
ds.PixelRepresentation = 0
ds.file_meta = file_meta
ds.is_implicit_VR = False
ds.is_little_endian = True
print(jpg_image.mode)
if jpg_image.mode == 'RGBA' or jpg_image.mode == 'RGB':
np_image = np.array(jpg_image.getdata(), dtype=np.uint8)[:,:3]
ds.Rows = jpg_image.height
ds.Columns = jpg_image.width
ds.PhotometricInterpretation = "RGB"
ds.SamplesPerPixel = 3
ds.BitsStored = 8
ds.BitsAllocated = 8
ds.HighBit = 7
ds.PixelRepresentation = 0
ds.PixelData = np_image.tobytes()
if jpg_image.mode == 'L':
np_image = np.array(jpg_image.getdata(),dtype=np.uint8)
ds.Rows = jpg_image.height
ds.Columns = jpg_image.width
ds.PhotometricInterpretation = "MONOCHROME1"
ds.SamplesPerPixel = 1
ds.BitsStored = 8
ds.BitsAllocated = 8
ds.HighBit = 7
ds.PixelRepresentation = 0
ds.PixelData = np_image.tobytes()
#np_image = np.array(jpg_image.getdata(), dtype=np.uint8)[:,:3]
#ds.PixelData = np_image.tobytes()
#ds.save_as('result_rgb.dcm')
## POST REQUEST (Sascha)
#post_data = {
#'sopInstanceUID':SOPInstanceUID,
#'description':description,
#}
#headers = {"Authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJCanRLSkdOYlF1REY5M28zNjRyZFVGbXh5SWdfMWJzcWM4UFRYUFZaOWRFIn0.eyJleHAiOjE2Nzk4Njk5NDcsImlhdCI6MTY3OTg2OTY0NywiYXV0aF90aW1lIjoxNjc5ODY1NTMyLCJqdGkiOiIzYjUxMDg3MS04N2Q2LTRhNTUtYmIyNi04YjM1YjcyY2RiZDgiLCJpc3MiOiJodHRwczovL3YwMDA1NTYuZmhudy5jaC9yZWFsbXMvRkhOVy1MU1QtTUkiLCJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMDBhZWExMjgtMzAyYS00Zjk1LTk4MTQtOThhOGZjMDYzYjU0IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiZzEtYXBwIiwibm9uY2UiOiI3NGJhNWI2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wp-ubEDnKjRNo9gI9e182PyPfh5XjFRSzkZfbVLuisCjwl3QiKubNzdTECSGfw"}
#r = requests.post(url = "https://v000561.fhnw.ch/spithub-api/api/images", json = post_data, headers=headers)
#print(r.text)
cursor.execute("INSERT INTO images (comment, description, sop_instanceuid, image_name, hue,saturation,brightness) VALUES (%s,%s,%s, %s,0,0,0)",( "", description,SOPInstanceUID,img['@src']))
conn.commit()
try:
image = Image.open(img['@src'])
image.thumbnail((100, 100))
image.save('/srv/spithub/static-content/thumbnails/'+img['@src'])
except IOError:
pass
# Use the C-STORE service to send the dataset
# returns the response status as a pydicom Dataset
status = assoc.send_c_store(ds)
# Check the status of the storage request
if status:
# If the storage request succeeded this will be 0x0000
print('C-STORE request status: 0x{0:04x}'.format(status.Status))
else:
print('Connection timed out, was aborted or received invalid response')
#ds.save_as(r'app11he_from_codify.dcm', write_like_original=False)
conn.close()
# Release the association
assoc.release()
else:
print('Association rejected, aborted or never connected')