Beispiel #1
0
    def AtrophyPrediction(self, roi):
        img = self.ModAtrophy.predict(roi)
        atrophyRate = met.atrophyRate(img)
        w, h, c = moil.getWidthHeightChannels(self.currentImg)
        img = cv2.resize(img,
                         (round(160 * w / 600), round(160 * (w * 0.75) / 450)))
        img = moil.getBinaryThreshold(img)

        return atrophyRate, img
Beispiel #2
0
    def predict(self, im):
        w, h, c = moil.getWidthHeightChannels(im)

        if w != self.colDim or h != self.rowDim or c != self.channels:
            im = cv2.resize(im, (self.colDim, self.rowDim))[:, :]
        im = self.prepareImage(im)
        im = self.model.predict(im)
        im = moil.convertImageNetOutput(im)
        return im
Beispiel #3
0
def registerImageCsv(repo_path, image_path, image_name, image, function):
    patient, date, eye = morn.getPatientDateEye(image_path)
    width, height, channels = moil.getWidthHeightChannels(image)
    func_name = function.__name__
    header = [
        'patient', 'date', 'eye', 'name', 'width', 'height', 'channels',
        'function'
    ]
    row = [patient, date, eye, image_name, width, height, channels, func_name]
    writeToCsv(repo_path + "imageData.csv", header, row)
Beispiel #4
0
    def OpticDiscPrediction(self):
        img = self.Mod.predict(self.currentImg)

        # img = moil.stackImageChannels(img)

        # resizing prediction
        w, h, c = moil.getWidthHeightChannels(self.currentImg)
        img = cv2.resize(img, (w, h))

        # getting coords
        x, y = met.getCenter(img, w, h)
        x = int(x)
        y = int(y)
        return x, y, img
Beispiel #5
0
def getCenter(pred, widthRef, heightRef, morph_iter=0, threshold=127):
    thresh = moil.getBinaryThreshold(pred, threshold)

    closed = moil.morphMultiClosing(thresh, morph_iter)
    contour = moil.selectBiggerCircularContour(closed)
    w, h, c = moil.getWidthHeightChannels(pred)
    try:
        M = cv2.moments(contour)
        cx = int(M['m10'] / M['m00'])
        cy = int(M['m01'] / M['m00'])

    except Exception as e:
        print("No contour detected! Guessing for center...")
        cx = int(w / 2)
        cy = int(h / 2)
    w_scale = widthRef / w
    h_scale = heightRef / h
    cx = cx * w_scale
    cy = cy * h_scale
    return cx, cy
Beispiel #6
0
    def circle_mask_on_random_image_in_path(self,
                                            path,
                                            target_size=None,
                                            r=None,
                                            extension=".jpg",
                                            check_csv=True,
                                            list=None):

        numb = len([
            i for i in os.listdir(path)
            if os.path.isfile(os.path.join(path, i))
        ])
        temp = ([
            a for a in os.listdir(path)
            if os.path.isfile(os.path.join(path, a))
        ])
        try:
            j = np.random.randint(numb)
        except:
            print(path + ", numb: " + str(numb))
            return

        ImName = random.choice(temp)
        if not os.path.exists(path + '/mask'):
            os.makedirs(path + '/mask')
        tempName = path + '/mask/' + ImName
        if os.path.exists(tempName):
            print("Path exists (" + tempName + ")")
            return
        if check_csv:
            paths = morn.getRepoPathAndImagePath(path)
            row = paths[1].split("/")[:-1]
            row.append(ImName)
            if mocl.checkIfExistsInCSV(row, paths[0], list, False):
                print("In CSV exists (" + tempName + ")")
                return

        if r is None and target_size is not None:
            self.rr = int(target_size[0] / 10)
        else:
            self.rr = r

        img = moil.read_and_size(ImName,
                                 path=path,
                                 target_size=target_size,
                                 extension='')
        w, h, c = moil.getWidthHeightChannels(img)
        if r is None and target_size is None:
            self.rr = int(w / 10)
            target_size = (w, h)
        moil.show(img)

        accepted = False
        while not accepted:
            accepted = True

            im2, contours, hierarchy = cv2.findContours(
                self.mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            im2 = copy.deepcopy(img)
            cv2.drawContours(im2, contours, 0, (0, 255, 255), 2)

            moil.show(im2)

        split_path = path.split("/")[:-1]

        repo_path = reduce((lambda x, y: x + '/' + y),
                           split_path[:len(split_path) - 3])
        if not os.path.isfile(repo_path + "/maskData.csv"):
            csvFile = open(repo_path + '/maskData.csv', 'w', newline="")
            writer = csv.writer(csvFile)
            writer.writerow([
                'patient', 'date', 'eye', 'name', 'width', 'height', 'x', 'y',
                'r'
            ])
            csvFile.close()

        csvFile = open(repo_path + '/maskData.csv', 'a', newline="")
        writer = csv.writer(csvFile)
        ls = split_path[-3:]
        ls.extend([
            ImName, target_size[0], target_size[1], self.xx, self.yy, self.rr
        ])
        writer.writerow(ls)
        csvFile.close()
        cv2.imwrite(path + '/mask/' + ImName, self.mask)
        self.masks_done += 1
        print("masks: " + str(self.masks_done))
        cv2.destroyWindow('mask')
Beispiel #7
0
    def make_prediction(self):
        x, y, pred = self.OpticDiscPrediction()
        self.x = x
        self.y = y
        copy = self.currentImg.copy()
        drawCopy = self.currentImg.copy()
        drawCopy = moil.stackImageChannels(drawCopy)
        w, h, c = moil.getWidthHeightChannels(copy)
        xShift = int(80 * w / 600)
        yShift = int(80 * (w * 0.75) / 450)

        xExitShift = int(40 * w / 600)
        yExitShift = int(40 * (w * 0.75) / 450)
        roi = moil.getRegionOfInterest(copy, x, y, xShift, yShift)
        roiExit = moil.getRegionOfInterest(copy, x, y, xExitShift, yExitShift)
        atrophyRate, atrophyMap = self.AtrophyPrediction(roi)
        self.atrophyRate = atrophyRate
        self.label.configure(
            text="Stopień zaniku (tylko faza tętniczo-żylna): " +
            str(atrophyRate))

        xExit, yExit = self.ExitPrediction(roiExit, xExitShift, yExitShift, x,
                                           y)
        self.xOut = xExit
        self.yOut = yExit
        dist = np.linalg.norm(
            np.asarray([xExit / w * 600, yExit / (w * 0.75) * 450]) -
            np.asarray([x / w * 600, y / (w * 0.75) * 450]))
        if dist > 16:
            self.labelExit.configure(
                text='Przesunięcie naczyń (faza tętniczo-żylna lub późna) : ' +
                str(dist) + ', ZNACZNE!')
        else:
            self.labelExit.configure(
                text='Przesunięcie naczyń (faza tętniczo-żylna lub późna) : ' +
                str(dist))
        wA, hA, cA = moil.getWidthHeightChannels(atrophyMap)

        mask = np.zeros((h, w), drawCopy.dtype)
        mask = moil.addToRegionOfInterest(mask, x, y, round(wA / 2 + 0.00001),
                                          round(hA / 2 + 0.00001), atrophyMap)

        # mask[y-round(hA/2+0.00001):y+round(hA/2+0.00001), x-round(wA/2+0.00001):x+round(wA/2+0.00001)] = atrophyMap
        redImg = np.zeros(drawCopy.shape, drawCopy.dtype)
        redImg[:, :] = (255, 0, 0)
        redMask = cv2.bitwise_and(redImg, redImg, mask=mask)
        drawCopy = cv2.addWeighted(redMask, 1, drawCopy, 1, 0)

        # moil.show(atrophyMap)
        # drawCopy[mask] = (255, 0, 0)
        cv2.rectangle(drawCopy, (x - xShift, y - yShift),
                      (x + xShift, y + yShift), (127, 0, 127),
                      int(5 / 1387 * w))
        cv2.circle(drawCopy, (x, y),
                   int(12 / 1387 * w), (127, 0, 127),
                   thickness=int(5 / 1387 * w))

        met.draw(pred, drawCopy, thickness=int(4 / 1387 * w))
        cv2.circle(drawCopy, (xExit, yExit),
                   int(12 / 1387 * w), (0, 127, 0),
                   thickness=int(5 / 1387 * w))
        self.updateGuiImage(drawCopy)
        self.predicted = True
Beispiel #8
0
def centerDiff(pred, true=None, x=None, y=None, width=None, height=None, r=None, morph_iter=0, threshold=127,
               toDraw=None, retDist=False):
    assert true is not None or (
            x is not None and y is not None and width is not None and height is not None and r is not None)

    thresh = moil.getBinaryThreshold(pred, threshold)

    closed = moil.morphMultiClosing(thresh, morph_iter)
    contour = moil.selectBiggerCircularContour(closed)
    if toDraw is not None and contour is not None:
        cv2.drawContours(toDraw, [contour], -1, (255, 255, 255), 1)

    w, h, c = moil.getWidthHeightChannels(pred)
    try:
        M = cv2.moments(contour)
        cx = int(M['m10'] / M['m00'])
        cy = int(M['m01'] / M['m00'])

    except Exception as e:
        print("No contour detected! Guessing for center...")
        cx = int(w / 2)
        cy = int(h / 2)

    if (x is None or y is None or width is None or height is None or r is None):

        width, height, chan = moil.getWidthHeightChannels(true)
        r = width / 10

        thresh = moil.getBinaryThreshold(true, threshold)

        im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        try:
            M = cv2.moments(contours[0])
            x = int(M['m10'] / M['m00'])
            y = int(M['m01'] / M['m00'])
        except:
            print("Bad Ground-truth! Mask in center...")
            x = int(w / 2)
            y = int(h / 2)

    w_scale = width / w
    h_scale = height / h
    cx = cx * w_scale
    cy = cy * h_scale

    dist = np.linalg.norm(np.asarray([cx, cy]) - np.asarray([x, y]))

    if retDist:
        return dist

    maxDist = np.linalg.norm(np.asarray([w / 2, h / 2]) - np.asarray([x, y]))

    DistanceMetric = 1 - dist / maxDist

    CrossLength = math.sqrt(width ** 2 + height ** 2)

    DistanceToCross = dist / CrossLength

    print("Distance Metric: " + str(DistanceMetric) + ", Relative Distance: " + str(
        DistanceToCross) + ", Distance: " + str(dist))

    return DistanceMetric