本文介绍了如何在opencv 2.4.11 python中调整轮廓的大小? (目标:对象提取)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是opencv的新手,请原谅我的无知...

I'm super new to opencv, so pardon my ignorance...

基本上:我的图像中有一个感兴趣的对象.我想提取它.

Basically: I have an object of interest in my image. I would like to extract it.

我的问题来自缩小原始图像的尺寸以便于处理.我在较小的图像上发现了物体的轮廓.我真正想做的是使用有关轮廓的信息从原始全尺寸图像中提取对象.

My problems arise from downscaling the original image in order to facilitate processing. I have found a contour of the object on the smaller image. What I would really like to do is use the information about that contour to extract the object from the original full size image.

我真的只能想到两种方法来实现此目的,但是我不知道在opencv中哪种方法真正有意义:

I can really only think of two ways to do this, but I have no idea which of these actually make sense in opencv:

  1. 调整轮廓大小.然后将其绘制在原始图像上.
  2. (我正在使用的那个,没有成功...)使用轮廓创建遮罩.调整遮罩的大小.然后将蒙版添加到原始图像.

我正在使用2号,但我认为面罩有问题.调整大小后,它不再包含轮廓.

I'm using No. 2, but I think there is a problem with the mask. Resized, it no longer contains the contour.

以下是我当前代码的重要部分:

Here are the important parts of my current code:

image = cv2.imread(path)
orig = image.copy()
...

#resize the image
image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
....

#convert to gray scale
...

#get contour
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
...
screenCnt = cv2.approxPolyDP(c, 0.01 * peri, True) #<--the contour
...

#create the mask
mask = np.ones(image.shape,np.uint8)*255
cv2.drawContours(mask,[screenCnt],0,(0,0,0),-1)
cv2.imshow("Small mask",mask) #<--- looks good
print(mask.shape) #<---returns a 3 element tuple
cv2.waitKey(0)

#now resize the mask
mask_big = cv2.resize(mask,(0,0),fx=ratio,fy=300)
cv2.imshow("Big mask",mask_big) #<--- ends up big, but all white (no contour)
cv2.waitKey(0)

我一直在搜寻互联网,但是没有运气,但是我想我在这里根本上缺少一些基本知识.感谢所有答复者一百万!

I've been scouring the internet without luck, but I think I'm missing something fundamental here.Thanks a million to all answerers!

推荐答案

我认为这是一个很老的问题.但是,我有相同的人,却无法通过代码示例快速找到答案.这是示例(适用于opencv 3.4)

As I see it is quite old question. However, I had the same one and was't able to find quick answer with sample of code. Here is the example (for opencv 3.4)

_, contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

coef_y = img_orig.shape[0] / img_resized.shape[0]
coef_x = img_orig.shape[1] / img_resized.shape[1]

for contour in contours:
    contour[:, :, 0] = contour[:, :, 0] * coef_x
    contour[:, :, 1] = contour[:, :,  1] * coef_y

    cv2.drawContours(img_orig, contour, -1, (0, 255, 0), 2)

这篇关于如何在opencv 2.4.11 python中调整轮廓的大小? (目标:对象提取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:28