如何提取多个图像的固定大小的ROI?
How to extract the fixed size ROI for multiple images?
我有一个图片文件夹。我想将对象提取为固定大小的 ROI,例如 (100*100) 并提取该对象的位置。我使用以下代码。但它只能将轮廓裁剪成各种矩形形状。我的目标是将对象提取到大小相等的框架中。我需要像以下样本一样,其中输出补丁的形状相同。
import cv2
import glob
def crop_brain_contour(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale
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]
#Make sure h < desired_height and w < desired_width
x1 = int(desired_width/2 - w/2)
y1 = int(desired_height/2 - h/2)
x2 = x1 + w
y2 = y1 + h
final_img[y1:y2, x1:x2, :] = img_crop
# Write the final image
cv2.imwrite("./extracted_data_1/image%04i.bmp" %i,final_img)
我有一个图片文件夹。我想将对象提取为固定大小的 ROI,例如 (100*100) 并提取该对象的位置。我使用以下代码。但它只能将轮廓裁剪成各种矩形形状。我的目标是将对象提取到大小相等的框架中。我需要像以下样本一样,其中输出补丁的形状相同。
import cv2
import glob
def crop_brain_contour(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale
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]
#Make sure h < desired_height and w < desired_width
x1 = int(desired_width/2 - w/2)
y1 = int(desired_height/2 - h/2)
x2 = x1 + w
y2 = y1 + h
final_img[y1:y2, x1:x2, :] = img_crop
# Write the final image
cv2.imwrite("./extracted_data_1/image%04i.bmp" %i,final_img)