Skip to content

Instantly share code, notes, and snippets.

@adyprat
Created September 5, 2023 14:27
Show Gist options
  • Save adyprat/25a0c22a7d02b71279ee9e7545ef4f94 to your computer and use it in GitHub Desktop.
Save adyprat/25a0c22a7d02b71279ee9e7545ef4f94 to your computer and use it in GitHub Desktop.
Import the 'Class' column from a csv file using the 'Object ID' map. Expects the 'Object ID's in csv match with the ones from the QuPath image.
import qupath.lib.scripting.QP
import qupath.lib.objects.classes.PathClass
import java.io.BufferedReader
import java.io.FileReader
import qupath.lib.io.*
def csvFilePath = Dialogs.promptForFile(null)
// Read the CSV file
def csvData = []
try {
def reader = new BufferedReader(new FileReader(csvFilePath))
def line
while ((line = reader.readLine()) != null) {
csvData.add(line.split(','))
}
reader.close()
} catch (Exception e) {
e.printStackTrace()
}
// Find the column indices for 'Object ID' and 'Class'
def objectIdIndex = -1
def classIndex = -1
def headerRow = csvData[0]
headerRow.eachWithIndex { value, index ->
if (value == 'Object ID') {
objectIdIndex = index
} else if (value == 'Class') {
classIndex = index
}
}
// Create the 'Object ID' to 'Class' map
def objectIdToClassMap = [:]
csvData.eachWithIndex { row, rowIndex ->
if (rowIndex > 0) {
def objectId = row[objectIdIndex]
def objectClass = row[classIndex]
objectIdToClassMap[objectId] = objectClass
}
}
// Print the 'Object ID' to 'Class' map
def pathClasses = getQuPath().getAvailablePathClasses()
print(pathClasses)
for (def detection : QP.getDetectionObjects()) {
def measurementList = detection.getMeasurementList()
objID = detection.getID().toString()
def newClassID = objectIdToClassMap[objID]
def newClass = PathClass.fromString(newClassID)
if (!pathClasses.contains(newClass)){
pathClasses.add(newClass)}
detection.setPathClass(newClass)
}
// Fire update event
println("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment