我正在尝试获取图像中bbox的坐标,并从图像中裁剪该区域。 我是opencv和python的新手
我尝试获取列表中的坐标列表并尝试将其传递。它给出了“ SystemError:tile无法扩展外部图像”错误。 我在这方面寻找答案,但听不懂。
import numpy as np
import imutils, cv2
import o
from PIL import Image
original_image = cv2.imread("04239713_02718309.tiff")
image = original_image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 120, 255, 1)
#cv2.imshow("edged", edged)
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
checkbox_contours = []
threshold_max_area = 3000
threshold_min_area = 375
contour_image = edged.copy()
cood=[]
allcoord=[]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.035 * peri, True)
x=0
y=0
w=0
h=0
(x, y, w, h) = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
area = cv2.contourArea(c)
if area < threshold_max_area and area > threshold_min_area and (aspect_ratio >= 0.9 and aspect_ratio <= 1):
cv2.drawContours(original_image,[c], 0, (0,255,0), 3)
#print(x,y,w,h)
temp=(x,y,w,h)
cood.append(temp)
checkbox_contours.append(c)
allcoord.append(cood)
print("cood",len(cood))
#print("allcoords",allcoord)
#print(allcoord)
print('checkbox_contours', len(checkbox_contours))
cv2.imwrite("peternass1.png", original_image)
print(cood)
org_image ='04239713_02718309.tiff'
for i, n in enumerate(cood):
image_obj = Image.open(org_image)
cropped_image = image_obj.crop(n)
os.system("{}.png".format(i))
cropped_image.save('Cro_{}.png'.format(i), 'png')
答案 0 :(得分:0)
我在这里使用opencv 4.0
您可以使用
找到轮廓contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
您可以在第一个轮廓周围绘制边框
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
x,y是边界的左上坐标
w是宽度(x坐标值),h是高度(y坐标值)
假设您的原始图片是
img = cv2.imread('myimage.jpg')
您可以使用
对其进行裁剪#x1,y1 = x,y(left top corner) and x2,y2 = x+w,y+h(right bottom corner)
selected_roi = img[y1:y2,x1:x2]