On another question (http://answers.opencv.org/question/70629/detect-spaces-and-fill-with-rectangle/ ) the solutions were coded in c++. Both work in c++. I choosed the @sturkmen solution because it is easier to implement.
However, I am struggling to convert to python. The structures are different, and it is being not easier to me find out some steps:
Here it is the c++ code: http://pastebin.com/EXuKpgY6
The original image:

The desired output:

And my python code as it is (not working):
def distanceBtwPoints(p0, p1):
return np.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
def findNearestPointIndex(pt, Points):
mindistance = 1e9
for ip in Points:
distance = distanceBtwPoints(pt, ip)
print distance
if distance < mindistance :
mindistance = distance
nearestpointindex = ip
return nearestpointindex
img = cv2.imread('mergepcbdrill1.jpg')
bw = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bw = np.asarray(bw < 127, dtype=np.uint8) # need to cast back to uint8
m1_contours, hier_m1 = cv2.findContours(bw, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
cnt = m1_contours[0]
for c in m1_contours:
if cnt.shape[0] < c.shape[0] :
cnt = c
for c in m1_contours:
if not np.array_equal(cnt, c) and c.shape[0] > 10:
for j in range(c.shape[0]):
pt0 = c[j][0]
cv2.line(img,pt0, m1_contours[findNearestPointIndex(pt0, np.vstack(cnt).squeeze())][0],
(0,0,0),1,8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.asarray(bw < 127, dtype=np.uint8) # need to cast back to uint8
m2_contours, hier_m2 = cv2.findContours(gray, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
gray = 255
for c2 in m2_contours:
cv2.drawContours(gray,[c2],-1,(0,0,0),1)
m_xor = np.ones(gray.shape, dtype="uint8") * 255
cv2.polylines(m_xor, cnt, False, (0,0,0), 1, 8)
m_xor = 255 - (gray or m_xor)
cv2.imwrite('result.jpg', m_xor)
↧