如何从多张图像中提取固定大小的感兴趣区域(ROI)?

我有一个包含多张图像的文件夹。我希望将对象提取为固定大小的ROI,例如(100*100),并提取该对象的位置。我使用了以下代码。但它只能将轮廓裁剪成各种矩形形状。我的目标是将对象提取到大小相等的框架中。我需要像以下样本那样的输出,其中输出的图像块形状相同。输入输出样本

        import cv2        import glob        def crop_brain_contour(image):            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 灰度化            cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL,   cv2.CHAIN_APPROX_SIMPLE)            cnts = cnts[0] if len(cnts) == 2 else cnts[1]            #ROI_number = 0            for c in cnts:               x,y,w,h = cv2.boundingRect(c)               ROI = image[y:y+h, x:x+w]               #cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)               #ROI_number += 1               return ROI        i=0        for img in glob.glob('./image_data/*.bmp'):           cv_img = cv2.imread(img)           img_crop = crop_brain_contour(cv_img)           #img_resize = cv2.resize(img_crop,(224,224))           cv2.imwrite("./extracted_data_1/image%04i.bmp" %i,img_crop)        i += 1       

回答:

在调用crop_brain_contour函数的地方进行以下更改:

desired_width, desired_height = (100, 100)final_img = np.zeros((desired_height, desired_width, 3), dtype="uint8")img_crop = crop_brain_contour(cv_img)h,w = img_crop.shape[:2]#确保h < desired_height 且 w < desired_widthx1 = int(desired_width/2 - w/2)y1 = int(desired_height/2 - h/2)x2 = x1 + wy2 = y1 + hfinal_img[y1:y2, x1:x2, :] = img_crop# 写入最终图像cv2.imwrite("./extracted_data_1/image%04i.bmp" %i,final_img)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注