Tutorial 8: Manual region segmentation

This tutorial demonstrates the classification of each spot based on our manual region segmentation by labelme software, and saves the region segmentation file (label.csv). Here, We use the human bronchiolar adenoma (BA) data generated by 10x Visium. The processed data can be downloaded from https://zenodo.org/record/8185216/files/Human_Bronchiolar_Adenoma.rar?download=1.

Preparation

[1]:
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import cv2
import pandas as pd
import numpy as np
import scanpy as sc
import matplotlib.pyplot as plt
import os
import sys
import json
from stGCL.process import prefilter_genes,prefilter_specialgenes,set_seed,refine_nearest_labels
from stGCL import utils
[2]:
address = "/home/dell/stproject/stGCL/Data/Human_Bronchiolar_Adenoma/spatial/tissue_hires_image.png"
image = cv2.imread(address)
f = open("/home/dell/stproject/stGCL/Data/Human_Bronchiolar_Adenoma/spatial/scalefactors_json.json", 'r')

content = f.read()
a = json.loads(content)
f.close()
scale = a["tissue_hires_scalef"]
img_new = image.copy()
[3]:
image_loc_in    = pd.read_csv('/home/dell/stproject/stGCL/Data/Human_Bronchiolar_Adenoma/spatial/tissue_positions_list.csv',
                              header = None, index_col = 0)
image_loc_in.columns=["isin","xarray","yarray","x","y",]
# image_loc_in["label"]="health"
image_loc_in.loc[image_loc_in["isin"]==1,"ground_truth"]="Normal"
[4]:
sh_fname        = '/home/dell/stproject/stGCL/Data/Human_Bronchiolar_Adenoma/HBA_label.json'
color_dict={"Bronchus":255,"Tumor":0,"Blood vessel":130}
with open(sh_fname, 'r') as f:
    sh_json = json.load(f)
Height=sh_json["imageHeight"]
Width=sh_json["imageWidth"]
[5]:
for sh in sh_json['shapes']:
    temp_celltype = sh['label']
    pts = np.squeeze(np.array(sh['points']))
    for i in pts:
        x = i[1] * scale* -1
        y = i[0] * scale* -1
        img_new[int(x - 4):int(x + 4), int(y - 4):int(y + 4), :] = color_dict[temp_celltype]
cv2.imwrite('/home/dell/stproject/stGCL/Data/Human_Bronchiolar_Adenoma/maplabel.jpg', img_new)
[5]:
True

Automatic label conversion

[6]:
for sh in sh_json['shapes']:
    temp_celltype = sh['label']
    id = sh['group_id']
    pts = np.squeeze(np.array(sh['points']))
    for barcode, imagerow, imagecol in zip(image_loc_in.index, image_loc_in["x"], image_loc_in["y"]):
        is_in = utils.judge_in(pts, (imagecol*-1+Width+0.00001, imagerow*-1+Height+0.00001))
        isin = image_loc_in.loc[barcode, "isin"]
        if is_in & isin==1:
            image_loc_in.loc[barcode, "ground_truth"]=temp_celltype
#             print(barcode,temp_celltype)
image_loc_in=image_loc_in.loc[image_loc_in["isin"] == 1]
image_loc_in["ground_truth"].to_csv("/home/dell/stproject/stGCL/Data/Human_Bronchiolar_Adenoma/label.csv")
print("conversion complete")
conversion complete