【发布时间】:2016-02-18 18:21:11
【问题描述】:
我使用 OpenCV 编写了一个 python 代码来访问图像,然后使用cv2.FindContours 函数提取了所有轮廓并过滤了具有最大周长的轮廓.
我的目标是现在将这个轮廓之外的所有像素变成黑色,只让这个轮廓内的像素变成白色。为此,我使用了cv.PointPolygonTest 函数,它告诉您一个点是否在多边形内。但是当我使用cv2.imwrite 编写我的结果时,我也很惊讶地看到图像旋转了,后来意识到它实际上是从左上角到右下角对角线的反射图像。
由于我的图像是矩形而不是正方形,这会导致我的某些感兴趣区域被截断。我附上代码和
输入图像
和输出图像
import cv2
import cv
import copy as cp
import numpy
im_gray = cv2.imread('1191res.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
im_gray2 = cp.copy(im_gray)
contours, hierarchy = cv2.findContours(im_gray2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#loop to calculate the relevant contour index
lperimeter = 0
i = 0
x = 0
while (x < len(contours)):
if(cv2.arcLength(contours[x], True) > lperimeter):
lperimeter = cv2.arcLength(contours[x],True)
i = x
x = x+1
#converting the contours[i] to a type recognized by function cv.PointPolygonTest
result = cv.fromarray(contours[i])
row = len(im_gray)
col = len(im_gray[0])
x = 0
print row
print col
nop = 0
r = 0
c = 0
while r < (row):
c = 0
while c < (col):
if( cv.PointPolygonTest(result,(r,c),False) == -1):
im_gray[r, c] = 0
nop+=1
else:
im_gray[r, c] = 255
c+=1
r+=1
print nop
cv2.imwrite("result1.jpg",im_gray)
【问题讨论】:
-
积分是
(x,y),即(col, row)。将您的代码更改为:if( cv.PointPolygonTest(result,(c,r),False) == -1): -
@Miki ...它成功了...谢谢....这很愚蠢!!!
-
很高兴它有帮助,然后作为答案发布