OpenCV和MATLAB中相同图像的强度值不同

时间:2016-03-03 19:49:17

标签: matlab python-2.7 opencv image-processing

我正在使用Python 2.7和OpenCV 3.x为我的项目使用网络摄像头进行omr表评估。

在找到圆心周围的白色像素数时,我发现强度值是错误的,但是当我使用imtool('a1.png')时,它在MATLAB中显示正确的值。

我正在使用.png图片(数据类型uint8)。 只需运行代码并在图像中转到[360:370,162:172]坐标并查看强度值..它不应该是0。 在这里找到图像 - > a1.png a2.png

为什么会这样?

import numpy as np
import cv2
from matplotlib import pyplot as plt
#select radius of circle
radius = 10;
#function for finding white pixels
def thresh_circle(img,ptx,pty):
    centerX = ptx;
    centerY = pty;
    cntOfWhite = 0;
    for i in range((centerX - radius),(centerX + radius)):
        for j in range((centerY - radius), (centerY + radius)):
            if(j < img.shape[0] and i < img.shape[1]):
                val = img[i][j]
                if (val == 255):
                    cntOfWhite = cntOfWhite + 1;
    return cntOfWhite

MIN_MATCH_COUNT = 10
img1 = cv2.imread('a1.png',0) # queryImage
img2 = cv2.imread('a2.png',0) # trainImage
sift = cv2.SIFT()# Initiate SIFT detector
kp1, des1 = sift.detectAndCompute(img1,None)# find the keypoints and descriptors with SIFT
kp2, des2 = sift.detectAndCompute(img2,None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)
good = []# store all the good matches as per Lowe's ratio test.
for m,n in matches:
    if m.distance < 0.7*n.distance:
        good.append(m)

if len(good)>MIN_MATCH_COUNT:
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)

    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.LMEDS,5.0)
    #print M
    matchesMask = mask.ravel().tolist()

    h,w = img1.shape
else:
    print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
    matchesMask = None

img3 = cv2.warpPerspective(img1, M, (img2.shape[1],img2.shape[0]))
blur = cv2.GaussianBlur(img3,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
ret,th2 = cv2.threshold(blur,ret3,255,cv2.THRESH_BINARY_INV)
print th2[360:370,162:172]#print a block of image
plt.imshow(th2, 'gray'),plt.show()
cv2.waitKey(0)
cv2.imwrite('th2.png',th2)
ptyc = np.array([170,200,230,260]);#y coordinates of circle center
ptxc = np.array([110,145,180,215,335,370,405,440])#x coordinates of circle center
pts_src = np.zeros(shape = (32,2),dtype=np.int);#x,y coordinates of circle center
ct = 0;
for i in range(0,4):
    for j in range(0,8):
        pts_src[ct][1] = ptyc[i];
        pts_src[ct][0] = ptxc[j];
        ct = ct+1;
boolval = np.zeros(shape=(8,4),dtype=np.bool)
ct = 0;
for j in range(0,8):
    for i in range(0,4):
        a1 = thresh_circle(th2,pts_src[ct][0],pts_src[ct][1])
        ct = ct+1;
        if(a1 > 50):
            boolval[j][i] = 1
        else:
            boolval[j][i] = 0

0 个答案:

没有答案