Skip to content

Instantly share code, notes, and snippets.

@3dimaging
Created June 27, 2018 16:06
Show Gist options
  • Save 3dimaging/c57c85d61eddb0c5b131eb94126551a6 to your computer and use it in GitHub Desktop.
Save 3dimaging/c57c85d61eddb0c5b131eb94126551a6 to your computer and use it in GitHub Desktop.
get annotation overlay with images by using python
#!/usr/bin/env python3
import multiresolutionimageinterface as mir
import matplotlib.pyplot as plt
import cv2
import numpy as np
reader = mir.MultiResolutionImageReader()
mr_image = reader.open('/home/wli/Downloads/tumor_036.tif')
Ximageorg, Yimageorg = mr_image.getDimensions()
dims = mr_image.getLevelDimensions(4)
#Ximage = (Ximage+240//2)//240
#Ximage = 4000
#Yimage = (Yimage+240//2)//240
#Yimage = 2000
import xml.etree.ElementTree as et
import pandas as pd
import math
def convert_xml_df (file):
parseXML = et.parse(file)
root = parseXML.getroot()
dfcols = ['Name', 'Order', 'X', 'Y']
df_xml = pd.DataFrame(columns=dfcols)
for child in root.iter('Annotation'):
for coordinate in child.iter('Coordinate'):
Name = child.attrib.get('Name')
Order = coordinate.attrib.get('Order')
X_coord = float(coordinate.attrib.get('X'))
# X_coord = X_coord - 30000
X_coord = ((X_coord)*dims[0])/Ximageorg
Y_coord = float(coordinate.attrib.get('Y'))
# Y_coord = Y_coord - 155000
Y_coord = ((Y_coord)*dims[1])/Yimageorg
df_xml = df_xml.append(pd.Series([Name, Order, X_coord, Y_coord], index = dfcols), ignore_index=True)
df_xml = pd.DataFrame(df_xml)
return (df_xml)
annotations = convert_xml_df('/home/wli/Downloads/tumor_036.xml')
x_values = list(annotations['X'].get_values())
y_values = list(annotations['Y'].get_values())
xy = list(zip(x_values,y_values))
#image = cv2.imread('/home/wli/Downloads/tumor_036.xml', -1)
tile =mr_image.getUCharPatch(0, 0, dims[0], dims[1], 4)
#canvas = np.zeros((Ximage, Yimage, 3), np.uint8) # fix the division
coords = np.array([xy], dtype=np.int32)
#cv2.drawContours(canvas, [coords],-1, (0,255,0), -1)
cv2.polylines(tile, [coords], isClosed=True, color=(0,0,255), thickness=5)
cv2.imshow("tile", tile);cv2.waitKey();cv2.destroyAllWindows()
#cv2.fillConvexPoly(mask, coords,1)
#mask = mask.astype(np.bool)
#output = np.zeros_like(image)
#output[mask] = image[mask]
#cv2.imshow('image',output)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
@qigongFDA
Copy link

I tried the code in windows. It is working. I find an interesting color problem
(We will not worry about color information now). The left image is from ASAP GUI, and the right one is from python. The colors are opposite: purple in GUI is displayed as pink in python, and pink in GUI is displayed as purpler in python.
comparecolor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment