最小外接矩形

该代码实现从医学影像数据中,针对`segmentation_results.dcm`和`data.dcm`文件,检测轮廓并计算最小外接矩形,然后将这个矩形区域裁剪出来。主要使用了OpenCV库进行图像处理,包括二值化、轮廓检测、边界框绘制等操作。对于不匹配的图像尺寸,将其记录在`shape_question`列表中。最终,裁剪后的图像保存到指定路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入:输出

 

完整代码:

import os
import pydicom
import matplotlib.pyplot as plt
import scipy.misc
import os
import pandas as pd
import SimpleITK as sitk
import pydicom
import numpy as np
import cv2
import time
import imageio
from PIL import Image
from  skimage import img_as_ubyte,io
import imageio

#-----------------------------------------------------#
#    label最小外接矩形 映射到data.dcm, 在小新电脑上运行没问题
#-----------------------------------------------------#

shape_question=[]
path=r"H:\good1"
save_path=r"H:\acquire"
for file in os.listdir(path):
    save_middle = os.path.join(save_path, file)
    if not os.path.exists(save_middle):
        os.makedirs(save_middle)
    path1=os.path.join(path,file)#"E:\good1\AN_MEI--91059740"


    for file1 in os.listdir(path1):#file1=[data.dcm,segmentation_results.dcm]
        if file1 =="segmentation_results.dcm":
            path_label=os.path.join(path1,file1)#"E:\good1\AN_MEI--91059740\segmentation_results.dcm"
        elif file1 == "data.dcm":
            path_data = os.path.join(path1, file1)  # "E:\good1\AN_MEI--91059740\segmentation_results.dcm"


    for img_label,img_data in zip(os.listdir(path_label),os.listdir(path_data)):
        img_label_path=os.path.join(path_label,img_label)
        img_data_path = os.path.join(path_data, img_data)
        #E:\good1\BAO_CONG_LIN--A829551\data.dcm\2.png

        label0 = Image.open(img_label_path)
        label0 = np.array(label0)

        data0 = Image.open(img_data_path)
        data0 = np.array(data0)
        if label0.shape!= data0.shape:
             shape_question.append(file)
        if np.max(label0) == True and np.max(data0) != 0 and img_label_path and img_data_path:
            im = cv2.imread(img_label_path)
            print('img_label_path',img_label_path)
            imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
            ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)  # 大津阈值
            contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # cv2.RETR_EXTERNAL 定义只检测外围轮廓
            cnts = contours[0]

            for cnt in cnts:
                # 外接矩形框,没有方向角
                x, y, w, h = cv2.boundingRect(cnt)
                cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2)
            pic = cv2.imread(img_data_path)  # 读取mask对应的图片
            print('img_data_path',img_data_path)
            print('h=',h)
            ge = pic[y:y + h, x:x + w]  # 根据内接矩形的顶点切割图片
            print('ge',ge)
            cv2.imwrite("H:/acquire/{0}/{1}".format(file,img_data),ge)
            print(1)
            img_label_path=None
            img_data_path=None
            label0=None
            data0=None


#
#
# print('---'*20)
# print('shape_question个数',len(set(shape_question)))
# for i in set(shape_question):
#     print(i)
# with open(r'C:\Users\Wu\Desktop\data.txt', mode='a', encoding='utf8') as f:
# # 文件写入
#     for i in set(shape_question):
#         f.write(i)
#         f.write('\n')

im = cv2.imread(r'D:\homeworks---homeworks\AN_MEI--91059740\segmentation_results.dcm\33.png')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)  # 大津阈值
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # cv2.RETR_EXTERNAL 定义只检测外围轮廓

# cnts = contours[0] if imutils.is_cv2() else contours[1]  # 用imutils来判断是opencv是2还是2+
cnts= contours[0]

for cnt in cnts:
    # 外接矩形框,没有方向角
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2)

pic = cv2.imread(r'D:\homeworks---homeworks\AN_MEI--91059740\data.dcm\33.png')  # 读取mask对应的图片
ge = pic[y:y + h, x:x + w]  # 根据内接矩形的顶点切割图片
cv2.imshow('ge', ge)
cv2.imwrite('./result/ge.jpg', ge)
cv2.waitKey(0)

    # # 最小外接矩形框,有方向角
    # rect = cv2.minAreaRect(cnt)
    # box = cv2.cv.Boxpoints() if imutils.is_cv2() else cv2.boxPoints(rect)
    # box = np.int0(box)
    # cv2.drawContours(im, [box], 0, (0, 0, 255), 2)

    # # 最小外接圆
    # (x, y), radius = cv2.minEnclosingCircle(cnt)
    # center = (int(x), int(y))
    # radius = int(radius)
    # cv2.circle(im, center, radius, (255, 0, 0), 2)
    #
    # # 椭圆拟合
    # ellipse = cv2.fitEllipse(cnt)
    # cv2.ellipse(im, ellipse, (255, 255, 0), 2)
    #
    # # 直线拟合
    # rows, cols = im.shape[:2]
    # [vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
    # lefty = int((-x * vy / vx) + y)
    # righty = int(((cols - x) * vy / vx) + y)
    # im = cv2.line(im, (cols - 1, righty), (0, lefty), (0, 255, 255), 2)

# cv2.imshow('original', im)
# # cv2.imwrite('./result.jpg', im)
# cv2.waitKey(0)

# # 将最小内接矩形填充为白色
# white = [255, 255, 255]
# for col in range(x, x + w):
#     for row in range(y, y + h):
#         im[row, col] = white
#
# cv2.imshow('label', im)
# # cv2.imwrite('./result.jpg', im)
# cv2.waitKey(0)

# pic = cv2.imread(r'D:\homeworks---homeworks\CAI_JI_YUN--91047991\data.dcm\63.png')  # 读取mask对应的图片
# ge = pic[y:y + h, x:x + w]  # 根据内接矩形的顶点切割图片
# cv2.imshow('ge', ge)
# cv2.imwrite('./result/ge.jpg', ge)
# cv2.waitKey(0)


































#
# def transform(label_path,data_path,subfolder):
#     im = cv2.imread(label_path)
#     imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
#     ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)  # 大津阈值
#     contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # cv2.RETR_EXTERNAL 定义只检测外围轮廓
#     cnts= contours[0]
#     for cnt in cnts:
#         # 外接矩形框,没有方向角
#         x, y, w, h = cv2.boundingRect(cnt)
#         cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2)
#
#     # # cv2.imwrite('./result.jpg', im)
#     # 将最小内接矩形填充为白色
#     # white = [255, 255, 255]
#     # for col in range(x, x + w):
#     #     for row in range(y, y + h):
#     #         im[row, col] = white
#     pic = cv2.imread(data_path)  # 读取mask对应的图片
#     ge = pic[y:y + h, x:x + w]  # 根据内接矩形的顶点切割图片
#
#     cv2.imwrite('./result/ge.jpg', ge)
#
#
path1=r'H:\good1\BAO_CONG_LIN--A829551\segmentation_results.dcm\40.png'
path2=r'H:\good1\BAO_CONG_LIN--A829551\data.dcm\40.png'
im = cv2.imread(path1)
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)  # 大津阈值
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # cv2.RETR_EXTERNAL 定义只检测外围轮廓
cnts = contours[0]

for cnt in cnts:
    # 外接矩形框,没有方向角
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2)
pic = cv2.imread(path2)  # 读取mask对应的图片
# print('img_data_path',img_data_path)
# print('h=',h)
ge = pic[y:y + h, x:x + w]  # 根据内接矩形的顶点切割图片
print('ge',ge)
cv2.imwrite("H:/acquire/1.png",ge)
# cv2.imwrite("H:/acquire/{0}/{1}".format(file,img_data),ge)
# print(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值