2016年5月31日 星期二

3D scan code study , step 3 and step 4


step3 :  threshold

=============================================
import numpy as np
import cv2
horzlino=1920
vertlino=1080
import os
import glob
img_names = glob.glob("CAML/*.png")
img1=cv2.imread(img_names[0],cv2.IMREAD_GRAYSCALE)
ii=50
# adjusting the threshold for processing area and eliminating shadows
# use left and right arrow key to adjust and press 'q' when finished

while True:
    ret,img1th = cv2.threshold(img1,ii,255,cv2.THRESH_TOZERO)
    cv2.putText(img1th,"Threshold is "+str(ii), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
    cv2.imshow("PWindow2",img1th)
    k = cv2.waitKey(0)
    if k == ord('q'):
        break
    elif k == ord('a'):
        ii=ii+1
    elif k == ord('b'):
        ii=ii-1

cv2.destroyAllWindows()

np.save(captdirect+"/"+"thresholdleft" , ii)
 
img_names = glob.glob("CAMR/*.png")
img1=cv2.imread(img_names[0],cv2.IMREAD_GRAYSCALE)
ii=50
while True:
    ret,img1th = cv2.threshold(img1,ii,255,cv2.THRESH_TOZERO)
    cv2.putText(img1th,"Threshold is "+str(ii), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
    cv2.imshow("PWindow2",img1th)
    k = cv2.waitKey(0)
    if k == ord('q'):
        break
    elif k == ord('a'):
        ii=ii+1
    elif k == ord('b'):
        ii=ii-1
     

cv2.destroyAllWindows()
np.save("thresholdright" , ii)  #  Save an array to a binary file in NumPy .npy format.
print 'Threshold Done!'


================================================================

step4 :  calcxy1xy2

================================================================


import numpy as np
import cv2
import os
import glob
old_settings = np.seterr(all='ignore')

horzlino=1920
vertlino=1080


Direct="CAMR/"
rightcamcode=np.load(Direct+"coloccod.npy" )  #  step 2  result,  right camcode,1920x1080x2 維度

                                                                                    [x][y][0] -> 放水平方向的 gray code 影像
                                                                                    [x][y][1] -> 放垂直方向的 gray code 影像

Direct="CAML/"
leftcamcode=np.load(Direct+"coloccod.npy" )   # step 2 result,  left camcode

thresholdleft=np.load("thresholdleft.npy" )        #  step 3 output thr val
thresholdright=np.load("thresholdright.npy" )    # step 3 output thr val

imgmaskrightf ="CAMR/CAM001.png"
img1=cv2.imread(imgmaskrightf,cv2.IMREAD_GRAYSCALE)  # Loads image in grayscale mode
ret,img1 = cv2.threshold(img1,thresholdright,255,cv2.THRESH_TOZERO) # TOZERO .. 小於thr 變成黑色...大於thr 維持不變
imgmaskright=np.divide(img1,img1)

=======================================================================
#   np.divide  

numpy.divide(x1x2[out]) = <ufunc 'divide'>
Divide arguments element-wise.
Parameters:
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs.
Returns:
y : ndarray or scalar
The quotient x1/x2, element-wise. Returns a scalar if both x1 andx2 are scalars.
np.divide(img1,img1)    -> 得到mask 只有0或是1 的影像
===================================================================
imgmaskleftf ="CAML/CAM101.png"
img1=cv2.imread(imgmaskleftf,cv2.IMREAD_GRAYSCALE)
ret,img1 = cv2.threshold(img1,thresholdleft,255,cv2.THRESH_TOZERO)
imgmaskleft=np.divide(img1,img1)

#  換成左邊做一次


kkl=0                #  kk coef for left
kkr=0                #  kk coef for right
colocright=[]     #  color array for right
colocleft=[]       #  color array for left
leftsrt=[]
rightsrt=[]

# finding similar points in both camera bast on projected pattern
for ii in range(0, horzlino):   # horzlino->  1920
    for jj in range(0, vertlino):  # vertlino->  1080
        if (rightcamcode[jj][ii][0]!=0 and rightcamcode[jj][ii][1]!=0 and imgmaskright[jj][ii]!=0):
           colocright.append(np.uint32([rightcamcode[jj][ii][0]+rightcamcode[jj][ii][1]*1024 ,ii, jj]))    
           #colocright 為一維陣列...  一次加三個值... color val,x , y
           rightsrt.append(rightcamcode[jj][ii][0]+rightcamcode[jj][ii][1]*1024)
           kkl=kkl+1
        if (leftcamcode[jj][ii][0]!=0 and leftcamcode[jj][ii][1]!=0 and imgmaskleft[jj][ii]!=0):
           colocleft.append(np.uint32([leftcamcode[jj][ii][0]+leftcamcode[jj][ii][1]*1024,ii ,jj]))
           leftsrt.append(leftcamcode[jj][ii][0]+leftcamcode[jj][ii][1]*1024)
           kkr=kkr+1

print kkr,kkl
np.savetxt("leftcod" , colocleft ,fmt='%d', delimiter=', ', newline='\n')
np.savetxt("rightcod" , colocright ,fmt='%d', delimiter=', ', newline='\n')

#  
numpy.savetxt(fnameXfmt='%.18e'delimiter=' 'newline='\n'header=''footer='',comments='# ')
fname : filename or file handle
If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.
X : array_like

Data to be saved to a text file.


import operator
colocrightsrt=[]
colocleftsrt=[]
colocrightsrt=sorted(colocright, key=operator.itemgetter(0))
colocleftsrt=sorted(colocleft, key=operator.itemgetter(0))
rightsrtt=sorted(rightsrt)
leftsrtt=sorted(leftsrt)

================================

numpy.sort

numpy.sort(aaxis=-1kind='quicksort'order=None)
Parameters:
a : array_like
Array to be sorted.
axis : int or None, optional
Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, optional
Sorting algorithm. Default is ‘quicksort’.
order : str or list of str, optional
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
Returns:
sorted_array : ndarray
Array of the same type and shape as a.
===========================
kkr=0
np.save("colocrightsrt" , colocrightsrt)
np.save("colocleftsrt" , colocleftsrt)
newlistl=np.unique(leftsrtt)
np.savetxt("colocleftsrtuniq" , newlistl ,fmt='%d', delimiter=', ', newline='\n')
newlistr=np.unique(rightsrtt)
np.savetxt("colocrightsrtuniq" , newlistr ,fmt='%d', delimiter=', ', newline='\n')

#finding common points in both cameras
camunio=np.intersect1d(newlistl,newlistr)


numpy.intersect1d(ar1ar2assume_unique=False)[source]
Find the intersection of two arrays.
Return the sorted, unique values that are in both of the input arrays.
Parameters:
ar1, ar2 : array_like
Input arrays.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Returns:
intersect1d : ndarray
Sorted 1D array of common and unique elements.
>>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
array([1, 3])


kkl=0
kkr=0
kk=0
matchpixels=np.zeros((np.size(camunio),4), dtype=np.int16)
matchpixels[kk][0]=0
matchpixels[kk][1]=0
matchpixels[kk][2]=0
matchpixels[kk][3]=0
for i in camunio:
    while (newlistr[kkr] != i):
        kkr=kkr+1
        matchpixels[kk][0]=colocrightsrt[kkr][1]  # right camera x pixel coordinate
        matchpixels[kk][1]=colocrightsrt[kkr][2]  # right camera y pixel coordinate
    while (newlistl[kkl] != i):
        kkl=kkl+1
        matchpixels[kk][2]=colocleftsrt[kkl][1]   #left camera x pixel coordinate
        matchpixels[kk][3]=colocleftsrt[kkl][2]   #left camera y pixel coordinate
    kk=kk+1
 

# 找到相同的亮度的座標...記錄left camera 的 (x,y) 放到  matchpixel[0][1]
                                                記錄right camera 的 (x,y) 放到  matchpixel[2][3]

np.savetxt("colocuniq" , matchpixels ,fmt='%d', delimiter=',', newline='\n')
print 'calcxy1xy2 Done!'




沒有留言:

張貼留言