如何将rois提取为单个roi图像

问题描述

我有一幅在透明图像中包含多个rois //非矩形//的图像。.plz帮助我如何将这些rois提取为独立的roi图像

plz help me how to extract those rois as induvidual roi image

解决方法

  1. 找到图像的contours

import cv2

img = cv2.imread("gzgSI.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,0)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    cv2.drawContours(img,[cnt],(0,0),3)

结果:

enter image description here

  1. 现在确定,我们已经检测到图像中的所有轮廓,可以分别保存它们。

    • 获取每个contour

      的坐标
      for i,cnt in enumerate(contours):
          x,y,width,height = cv2.boundingRect(cnt)
      
    • 设置图像中的坐标

      roi = img[y:y+height,x:x+width]
      
    • 一些示例结果:

      enter image description here enter image description here enter image description here enter image description here enter image description here

  • 在运行代码之前,请确保已创建rois文件夹。

代码:

import cv2

img = cv2.imread("gzgSI.jpg")
gray = cv2.cvtColor(img,cv2.CHAIN_APPROX_SIMPLE)

for i,height = cv2.boundingRect(cnt)
    roi = img[y:y+height,x:x+width]
    cv2.imwrite("rois/roi{}.png".format(i),roi)
,
import numpy as np
import matplotlib.pyplot as plt

!mkdir /content/test
!rm -r /content/test/*
image = cv2.imread('/content/test.png')
original = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray,(3,3),0)
canny = cv2.Canny(blurred,120,1)
kernel = np.ones((5,5),np.uint8)
dilate = cv2.dilate(canny,kernel,iterations=1)

# Find contours
cnts = cv2.findContours(dilate,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

# Iterate thorugh contours and filter for ROI
image_number = 0
for c in cnts:
    x,w,h = cv2.boundingRect(c)
    #cv2.rectangle(image,(x,y),(x + w,y + h),(36,12),2)
    ROI = original[y:y+h,x:x+w]
    #cv2.imwrite("/content/test/ROI_{}.png".format(image_number),ROI)
    image_number += 1

## (4) Create mask and do bitwise-op
mask = np.zeros(image.shape[:2],np.uint8)
cv2.drawContours(mask,[c],-1,-1)
dst = cv2.bitwise_and(image,image,mask=mask)

## Save it
#cv2.imwrite("dst.png",dst)
cv2.imwrite("/content/test/ROI_{}.png".format(image_number),dst)
image_number += 1



# cv2.imshow('canny',canny)
# cv2.imshow('image',image)
# cv2.waitKey(0)

plt.imshow(canny)
plt.imshow(image)here