我向Dicom服务器发出Get请求,该服务器返回Multipart / Related Type = image / jpeg。我尝试使用aiohttp libararies Multipart功能来解析,但是没有用。保存的文件已损坏。

这是我的代码。

    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))


如何解析Multipart /相关响应并保存图像?

最佳答案

我发现自己正在正确解析多部分响应,但是我不得不使用另一个库(库名:imagecodecs,方法名:jpegsof3_decode)将单个部分解压缩到图像中。这给出了图像的numpy数组。这是更新的代码

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)


此外,可以使用cv2 libray将numpy数组转换为图像

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


可以通过这种方式获得转换后图像的字节版本

imageInBytes = encoded_image.tobytes()

关于python - 如何解析和保存Multipart/related type = image/jpeg响应? (Dicom Wado回复),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58125826/

10-12 02:47