How to parse and save a Multipart/related type=image/jpeg response? (Dicom Wado Response)

1.2k views Asked by At

I'm making a Get request to Dicom server, which returns a Multipart/Related Type=image/jpeg. I tried using aiohttp libararies Multipart feature to parse but it didnt work. The file saved is corrupted.

Here is my code.

    import asyncio
    import aiohttp
    '''
    async def fetch(url,session,header):
        async with session.get(url,headers=header) as response:
             await response

    async def multiHit(urls,header):
        tasks = []
        async with aiohttp.ClientSession() as session:
            for i,url in enumerate(urls):
                tasks.append(fetch(url,session,header))
            result = await asyncio.gather(*tasks)
            return result

    loop = asyncio.get_event_loop()
    res = loop.run_until_complete(multiHit(["FRAME URL"],{"Accept":"multipart/related;type=image/jpeg"}))
    print(res)
    '''

    async def xyz(loop):
        async with aiohttp.ClientSession(loop=loop).get(url="FRAME URL",headers={"Accept":"multipart/related;type=image/jpeg"}) as response:
             reader = aiohttp.MultipartReader.from_response(response)
             while True:
                 part = await reader.next()
                 if part is None:
                     break
                 filedata = await part.read(decode=False)
                 import base64
                 with open('m.jpeg','wb') as outFile:
                     outFile.write(part.decode(filedata))
        return 1

    loop = asyncio.get_event_loop()
    res = loop.run_until_complete(xyz(loop))

How to I parse the Multipart/related response and save the images?

1

There are 1 answers

0
Vikas NS On BEST ANSWER

I figured out that I was parsing the multi-part response properly, but I had to use another library (library name : imagecodecs , method name : jpegsof3_decode) to decompresses individual part into the images. This is give a numpy array of the image. Here is the updated code

reader = aiohttp.MultipartReader.from_response(response)
while True:
     part = await reader.next()
     if part is None:
              break
     data = await part.read()
     imageDecompressed = jpegsof3_decode(data)

Further the numpy array can be converted into a image using cv2 libray

success, encoded_image = cv2.imencode('.png',imageDecompressed)

Byte version of the converted image can be obtained this way

imageInBytes = encoded_image.tobytes()