コード例 #1
0
def main():
    imageDir = r"C:\Study\test\bone\pic-test"
    pmSavingDir = r"C:\Study\test\bone\preprocess\pm-results"
    claheSavingDir = r"C:\Study\test\bone\preprocess\clahe-results"
    cropSavigDir = r"C:\Study\test\bone\preprocess\crop-results"
    util.mkdirs([pmSavingDir, claheSavingDir, cropSavigDir])

    picFiles = api.getFiles(imageDir)
    total = len(picFiles)

    for i, f in enumerate(picFiles):
        imgFileName = os.path.basename(f)
        print("[info] process {} / {}, img: {}".format(i + 1, total,
                                                       imgFileName))
        img = cv2.imread(f, 0)

        # # 去噪
        denoiseImg = PmDenoise(img)
        denoiseSavingPath = os.path.join(pmSavingDir, imgFileName)
        cv2.imwrite(denoiseSavingPath, denoiseImg)

        # 增强
        denoiseImg = cv2.imread(denoiseSavingPath, cv2.IMREAD_GRAYSCALE)
        claheImg = CLAHE(denoiseImg)
        cv2.imwrite(os.path.join(claheSavingDir, imgFileName), claheImg)

    # 为方便函数调用,最后统一裁剪
    crop(claheSavingDir, cropSavigDir)
コード例 #2
0
def handle(dirs, out_dir, clip):
    start_time = datetime.datetime.now()
    if not os.path.isdir(out_dir):
        os.mkdir(out_dir)
    files = getFiles(dirs)

    total = len(files)
    fail, success, skip, count = 0, 0, 0, 0

    for f in files:
        count += 1
        print(count, '/', total)
        img_dirs = os.path.join(out_dir, f.split("\\")[-1])
        if os.path.isfile(img_dirs):
            skip += 1
            continue
        try:
            # 读取图片
            img = cv2.imread(f, 0)
            # 切边
            x, w, y, h = clip
            img = img[x:w, y:h]
            # 去除噪点
            img = moveNoise(img, 7)
            # 根据最大熵算法获得最佳阈值
            threshed = maxEntrop(img)

            # 二值化
            threshold, thrshed_img = cv2.threshold(img, threshed * 0.4, 255,
                                                   cv2.THRESH_BINARY)
            saveImage(img_dirs, "_threshed_raw", thrshed_img)

            # 使用区域生长法分割
            img_segement, thresh_img = regionGrowing(img, thrshed_img)
            saveImage(img_dirs, "_threshed", thresh_img)

            # 去除多余边缘
            img_remove_margin = moveMargin(img_segement, thresh_img)
            saveImage(img_dirs, "_remove_margin", img_remove_margin)

            # 扩充为正方形并缩小为256x256
            img_new = normalization(img_remove_margin)
            saveImage(img_dirs, "_new", img_new)

            # 打印信息到输出台
            printToConsole(start_time, f, count, total, 5)
            success += 1
        except Exception as e:
            # 错误情况
            saveError(e, out_dir, f)
            fail += 1

    end_time = datetime.datetime.now()
    expend = end_time - start_time
    print(
        "\n\ntotal: %d\nsuccessful: %d\nskip: %d\nfailed: %d\nExpend time: %s"
        % (total, success, skip, fail, expend))
    os.startfile(out_dir)
コード例 #3
0
def testPM():
    imageDir = r"C:\Study\test\bone\pic-test"
    outputDir = r"C:\Study\test\bone\pm-results"
    util.mkdirs(outputDir)

    picFiles = api.getFiles(imageDir)
    total = len(picFiles)
    for it, file in enumerate(picFiles):
        print("[info] process {} / {}.".format(it + 1, total))
        img = cv2.imread(file, 0)
        retPic = PmDenoise(img, iter=2)
        savePath = os.path.join(outputDir, os.path.basename(file))
        # print(savePath)
        cv2.imwrite(savePath, retPic)
コード例 #4
0
def handle(dirs, out_dir, clip):
    start_time = datetime.datetime.now()
    if not os.path.isdir(out_dir):
        os.mkdir(out_dir)
    files = getFiles(dirs)

    total = len(files)
    fail, success, skip, count = 0, 0, 0, 0

    for f in files:
        count += 1
        print(count, '/', total)
        img_dirs = os.path.join(out_dir, f.split("\\")[-1])
        if os.path.isfile(img_dirs):
            skip += 1
            continue
        try:
            # 读取图片
            img = cv2.imread(f, 0)
            # 切边
            x, w, y, h = clip
            img = img[x:w, y:h]
            # 去除噪点
            img = moveNoise(img, 7)
            # 获得图像像素均值
            threshed = getMean(img)
            # 二值化
            threshold, thrshed_img = cv2.threshold(img, threshed * 0.86, 255,
                                                   cv2.THRESH_BINARY)
            # 使用轮廓法(速度快)分割
            img_segement, thresh_img = maxContour(img, thrshed_img)
            # 保存
            saveImage(img_dirs, "_new", img_segement)

            # 打印信息到输出台
            printToConsole(start_time, f, count, total, 5)
            success += 1
        except Exception as e:
            # 错误情况
            saveError(e, out_dir, f)
            fail += 1

    end_time = datetime.datetime.now()
    expend = end_time - start_time
    print(
        "\n\ntotal: %d\nsuccessful: %d\nskip: %d\nfailed: %d\nExpend time: %s"
        % (total, success, skip, fail, expend))
    os.startfile(out_dir)
コード例 #5
0
def handle(dirs, out_dir, clip, w0):
    start_time = datetime.datetime.now()
    if not os.path.isdir(out_dir):
        os.mkdir(out_dir)
    files = getFiles(dirs)

    total = len(files)
    fail, success, skip, count = 0, 0, 0, 0

    for f in files:
        count += 1
        print(count, '/', total)
        img_dirs = os.path.join(out_dir, f.split("\\")[-1])
        if os.path.isfile(img_dirs):
            skip += 1
            continue
        try:
            # 读取图片
            img = cv2.imread(f, 0)
            # 切边
            x, w, y, h = clip
            img = img[x:w, y:h]
            # 去除噪点
            thresh_value = getThreshValuebyHistogram(img, w0, is_handle=False)
            # 二值化
            threshold, thrshed_img = cv2.threshold(img, thresh_value, 255,
                                                   cv2.THRESH_BINARY)
            # 使用区域生长法分割
            img_segement, thresh_img = regionGrowing(img, thrshed_img)
            # 保存
            saveImage(img_dirs, "_new", img_segement)
            # 打印信息到输出台
            printToConsole(start_time, f, count, total, 5)
            success += 1
        except Exception as e:
            # 错误情况
            saveError(e, out_dir, f)
            fail += 1

    end_time = datetime.datetime.now()
    expend = end_time - start_time
    print(
        "\n\ntotal: %d\nsuccessful: %d\nskip: %d\nfailed: %d\nExpend time: %s"
        % (total, success, skip, fail, expend))
    os.startfile(out_dir)
コード例 #6
0
def cropImgUsingMarginInfo(marginInfoPath, imageDir, outputDir):
    """切边, 需保证待切边图片与marginInfo中的图片名称一致"""
    files = api.getFiles(imageDir)
    total = len(files)
    marginInfo = pickle.load(open(marginInfoPath,'rb'))
    util.mkdirs(outputDir)

    for i, f in enumerate(files):
        basename = os.path.basename(f)
        print("process {} / {}: {}".format(i+1, total, basename))

        img = cv2.imread(f, 0)

        if basename not in marginInfo:
            print("process {} / {}: {}, skip cause current pic name does not find in marginInfo".format(i+1, total, basename))
            continue

        margin = marginInfo[basename]
        retImg = crop.cropImage(img, margin)
        cv2.imwrite(os.path.join(outputDir, basename), retImg)
コード例 #7
0
def handle(dirs, out_dir):
    start_time = datetime.datetime.now()
    if not os.path.isdir(out_dir):
        os.mkdir(out_dir)
    files = getFiles(dirs)

    total = len(files)
    fail, success, skip, count = 0, 0, 0, 0

    for f in files:
        count += 1
        print(count, '/', total)
        img_dirs = os.path.join(out_dir, f.split("\\")[-1])
        if os.path.isfile(img_dirs):
            skip += 1
            continue
        try:
            img = cv2.imread(f, 0)
            # img_new = moveMargin(img, img)
            img_new = normalization(img_new)
            saveImage(img_dirs, "", img_new)

            # 打印信息到输出台
            printToConsole(start_time, f, count, total, 5)
            success += 1
        except Exception as e:
            # 错误情况
            saveError(e, out_dir, f)
            fail += 1

    end_time = datetime.datetime.now()
    expend = end_time - start_time
    print(
        "\n\ntotal: %d\nsuccessful: %d\nskip: %d\nfailed: %d\nExpend time: %s"
        % (total, success, skip, fail, expend))
    os.startfile(out_dir)
コード例 #8
0
def handle(dirs, out_dir, clip):
    """
    随机选取20张图片,在像素平均值附近取值
    dirs: 原图路径,20张图片
    out_dir: 二值图片输出路径
    clip = (30,-30,30,-30)
    """
    if not os.path.isdir(out_dir):
        os.mkdir(out_dir)

    files = getFiles(dirs)

    # 在label.txt里加上阈值
    out_label = os.path.join(out_dir, 'label.txt')
    label_file = open(out_label, "w")

    out_data = os.path.join(out_dir, 'data.txt')
    data_file = open(out_data, "w")

    # 原图对应序号
    record = os.path.join(out_dir, 'record.txt')
    record_file = open(record, "w")

    count = 0
    for f in files:

        record_data = str(count) + '\t' + str(f) + '\n'
        record_file.write(record_data)
        # continue

        img = cv2.imread(f, 0)

        # 裁剪边缘
        x, w, y, h = clip
        img = img[x:w, y:h]

        ######### 二值处理 ##########
        img_w, img_h = img.shape
        # 去噪
        img_med = cv2.medianBlur(img, 5)
        kernel = np.zeros((7, 7), np.uint8)
        thresh = cv2.morphologyEx(img_med, cv2.MORPH_OPEN, kernel)

        # 不同阈值处理
        # 计算均值
        sums = 0
        for i in range(img_w):
            for j in range(img_h):
                sums += thresh[i][j]
        mean_value = sums // (img_w * img_h)
        print()

        # 计算方差的
        sum_diff = 0
        for i in range(img_w):
            for j in range(img_h):
                diff = float(
                    (mean_value - thresh[i][j]) * (mean_value - thresh[i][j]))
                sum_diff += diff
        # print(sum_diff)
        variance = int((sum_diff // (img_w * img_h))**0.5)
        print("mean value: ", mean_value, ", variance: ", variance)

        # 计算直方图
        histogram = [0 for _ in range(256)]
        for i in range(img_w):
            for j in range(img_h):
                histogram[thresh[i][j]] += 1
        # print(histogram)
        for i in range(len(histogram)):
            histogram[i] = str(histogram[i])

        # 写入数据
        # 先写入均值 直方图 方差 数据 至 data.txt

        # histogram转换类型
        for i in range(len(histogram)):
            histogram[i] = str(histogram[i])

        data = str(count) + "\t" + str(mean_value) + "\t" + str(
            variance) + '\t' + "\t".join(histogram) + '\n'
        data_file.write(data)

        # 写入标签数据至label.txt
        label = str(count) + "\t" + str(mean_value) + "\t" + str(
            variance) + '\n'
        label_file.write(label)

        # 获取n个阈值
        n = 20
        gap = 2  # 两个阈值之间的间隔
        thresh_value = []
        small = mean_value
        left = 0
        while small > 0 and left < n:
            thresh_value.append(small)
            small -= gap
            left += 1

        # 大于均值的很差,所以不考虑了
        large = mean_value
        r = 5
        right = 0
        while large < 255 and right < r:
            thresh_value.append(large)
            large += 2
            right += 1

        for v in thresh_value:
            ret, new_thresh = cv2.threshold(thresh, v, 255, cv2.THRESH_BINARY)
            kernel = np.zeros((7, 7), np.uint8)
            new_thresh = cv2.morphologyEx(new_thresh, cv2.MORPH_CLOSE, kernel)
            new_thresh = cv2.medianBlur(new_thresh, 5)

            # 保存
            basename = os.path.basename(f)
            file = os.path.splitext(basename)
            file_prefix = str(count)  # file[0]
            file_suffix = file[-1]
            if v == mean_value:
                image_name = file_prefix + '_thresh_value_' + str(
                    v) + '_mean' + file_suffix
            else:
                image_name = file_prefix + '_thresh_value_' + str(
                    v) + file_suffix
            out_file = os.path.join(out_dir, image_name)
            print("saving :", out_file)
            cv2.imwrite(out_file, new_thresh)

        count += 1

    data_file.close()
    label_file.close()
    record_file.close()
    os.startfile(out_dir)
コード例 #9
0
def process(imageDir, outputDir):
    """使用DBSACN裁剪图片"""
    files = api.getFiles(imageDir)
    total = len(files)

    pointsDir = os.path.join(outputDir, "points")
    cluserDir = os.path.join(outputDir, "cluster")
    cropDir = os.path.join(outputDir, "crop")
    util.mkdirs([cluserDir, cropDir, pointsDir])

    marginInfo = {}
    for i, f in enumerate(files):
        basename = os.path.basename(f)
        print("[info] crop image, process {} / {}: {}".format(
            i + 1, total, basename))
        img = cv2.imread(f)

        cropImg = moveMargin(img, (45, -45, 45, -45))  # 删除边框特征

        maxMargin = None
        method = ["SIFT", "SURF", "ORB"]
        mergePoints = []
        for m in method:
            img = copy.deepcopy(cropImg)
            curpointsDir = os.path.join(pointsDir, m)
            curcluserDir = os.path.join(cluserDir, m)
            curcropDir = os.path.join(cropDir, m)
            util.mkdirs([curcluserDir, curcropDir, curpointsDir])

            points = getROIPoint(img, f=m)  # 获得ROI点

            # 保存ROI
            pointsSavePath = os.path.join(curpointsDir, basename)
            savePointsImg(pointsSavePath, points, img.shape)

            try:
                maxCluster = getMaxCluster(points, 40)  # 获得最大聚类
            except:
                print("[error] skip: {}".format(basename))
                continue
            mergePoints.extend(maxCluster)  # 融合特征点

            # 保存关键点图像
            clusterSavePath = os.path.join(curcluserDir, basename)
            savePointsImg(clusterSavePath, maxCluster, img.shape)

            margin = getMargin(maxCluster)  # 获得边界点u, r, d, l
            if not maxMargin:
                maxMargin = margin
            else:
                u, r, d, l = margin
                maxMargin[0] = min(maxMargin[0], u)
                maxMargin[1] = max(maxMargin[1], r)
                maxMargin[2] = max(maxMargin[2], d)
                maxMargin[3] = min(maxMargin[3], l)

            retImg = cropImage(img, margin)  # 裁剪图片

            # 保存裁剪结果
            cropSavePath = os.path.join(curcropDir, basename)
            cv2.imwrite(cropSavePath, retImg)

        # 三种方法获得的最大边界
        w, h = img.shape[0], img.shape[1]
        if maxMargin[0] - up < 0:
            maxMargin[0] = 0
        else:
            maxMargin[0] -= up

        if maxMargin[1] + right > w:
            maxMargin[1] = w - 1
        else:
            maxMargin[1] += right
        # 图片下边缘不补偿
        if maxMargin[3] - left < 0:
            maxMargin[3] = 0
        else:
            maxMargin[3] -= left

        marginInfo[basename] = maxMargin  # 记录切边信息
        retImg = cropImage(img, maxMargin)  # 裁剪图片

        # 保存不同特征点融合图像
        mergeSavePath = os.path.join(pointsDir,
                                     "mergePoints_{}".format(basename))
        savePointsImg(mergeSavePath, mergePoints, img.shape)

        # 保存裁剪结果
        cropSavePath = os.path.join(cropDir, basename)
        cv2.imwrite(cropSavePath, retImg)

        # if i == 5: assert False, 'break'

    writeMarginInfo(os.path.join(outputDir, "marginInfo.txt"),
                    marginInfo)  # 保存到结果目录

    os.startfile(outputDir)
コード例 #10
0
def genDiffPicByThresholdValue(imgDir, outputDir):
	files = api.getFiles(imgDir)

	util.mkdirs(outputDir)
コード例 #11
0
def process(imageDir, outputDir):
    """使用DBSACN裁剪图片"""
    files = api.getFiles(imageDir)
    total = len(files)

    pointsDir = os.path.join(outputDir, "points")
    cluserDir = os.path.join(outputDir, "cluster")
    cropDir = os.path.join(outputDir, "crop")
    util.mkdirs([cluserDir, cropDir, pointsDir])

    marginInfo = {}
    for i, f in enumerate(files):
        basename = os.path.basename(f)
        print("process {} / {}: {}".format(i+1, total, basename))
        img = cv2.imread(f)

        maxMargin = None
        method = ["SIFT", "SURF", "ORB"]
        for m in method:
            curpointsDir = os.path.join(pointsDir, m)
            curcluserDir = os.path.join(cluserDir, m)
            curcropDir = os.path.join(cropDir, m)
            util.mkdirs([curcluserDir, curcropDir, curpointsDir])


            points = getROIPoint(img)               # 获得ROI点

            # 保存ROI
            pointsSavePath = os.path.join(curpointsDir, basename)
            savePointsImg(pointsSavePath, points, img.shape)


            maxCluster = getMaxCluster(points, 40)  # 获得最大聚类

            # 保存关键点图像
            clusterSavePath = os.path.join(curcluserDir, basename)
            savePointsImg(clusterSavePath, maxCluster, img.shape)

            margin = getMargin(maxCluster)  # 获得边界点u, r, d, l
            if not maxMargin:
                maxMargin = margin
            else:
                u, r, d, l = margin
                maxMargin[0] = min(maxMargin[0], u) 
                maxMargin[1] = max(maxMargin[1], r) 
                maxMargin[2] = max(maxMargin[2], d) 
                maxMargin[3] = min(maxMargin[3], l) 

            retImg = cropImage(img, margin) # 裁剪图片

            # 保存裁剪结果
            cropSavePath = os.path.join(curcropDir, basename)
            cv2.imwrite(cropSavePath, retImg)

        # 三种方法获得的最大边界
        h, w = img.shape[0], img.shape[1]
        print
        if maxMargin[0] - up < 0:
            maxMargin[0] = 0
        else:
            maxMargin[0] -= up

        if maxMargin[1] + right > w:
            maxMargin[1] = w - 1
        else:
            maxMargin[1] += right

        if maxMargin[3] - left < 0:
            maxMargin[3] = 0
        else:
            maxMargin[3] -= left

        marginInfo[basename] = maxMargin    # 记录切边信息
        retImg = cropImage(img, maxMargin)  # 裁剪图片

        # 保存裁剪结果
        cropSavePath = os.path.join(cropDir, basename)
        cv2.imwrite(cropSavePath, retImg)

    writeMarginInfo(os.path.join(outputDir, "marginInfo.txt"), marginInfo)   # 保存到结果目录

    os.startfile(outputDir)