def paddingAnswers(answerSheet1, blankSheet1):
   numRowsA, numColsA, numBandsA, dataTypeA = ipcv.dimensions(answerSheet1)
   numRowsB, numColsB, numBandsB, dataTypeB = ipcv.dimensions(blankSheet1)
   print numRowsB, numColsB
   if numBandsA == 3:
      answerSheet = cv2.cvtColor(answerSheet1, cv.CV_BGR2GRAY)
   elif numBandsA == 1:
      answerSheet = answerSheet1

   if numBandsB == 3:
      blankSheet = cv2.cvtColor(blankSheet1, cv.CV_BGR2GRAY)
   elif numBandsB == 1:
      blankSheet = blankSheet1  

   pad = numpy.absolute(numRowsA - numColsA)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsA-numColsA) % 2 != 0:
      answerSheet = numpy.pad(answerSheet, ((0,0),(pad,pad+1)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsA-numColsA) % 2 == 0:
      answerSheet = numpy.pad(answerSheet, ((0,0),(pad,pad)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))

   pad1 = numpy.absolute(numRowsB - numColsB)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsB-numColsB) % 2 != 0:
      blankSheet = numpy.pad(blankSheet, ((0,0),(pad1,pad1+1)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsA-numColsA) % 2 == 0:
      blankSheet = numpy.pad(blankSheet, ((0,0),(pad1,pad1)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))


   return answerSheet, blankSheet
Beispiel #2
0
def register(fid1, fid2, fid3, image, blank):
   numRows, numCols, numBands, dtype = ipcv.dimensions(blank)
   
   blank1row, blank1col = ipcv.fftCorrelation2(fid1,blank)
   blank2row, blank2col = ipcv.fftCorrelation2(fid2,blank)
   blank3row, blank3col = ipcv.fftCorrelation2(fid3,blank)

   print 'blank1row', blank1row
   print 'blank1col', blank1col
   print 'blank2row', blank2row
   print 'blank2col', blank2col
   print 'blank3row', blank3row
   print 'blank3col', blank3col
  

   #blankfid1 = numpy.array([738,60])
   #blankfid2 = numpy.array([738,542])
   #blankfid3 = numpy.array([53,556])
   
   #print blankfid2.shape

   fid1row, fid1col = ipcv.fftCorrelation2(fid1,image)
   fid2row, fid2col = ipcv.fftCorrelation2(fid2,image)
   fid3row, fid3col = ipcv.fftCorrelation2(fid3,image)

   print 'fid1row', fid1row
   print 'fid1col', fid1col
   print 'fid2row', fid2row
   print 'fid2col', fid2col
   print 'fid3row', fid3row
   print 'fid3col', fid3col
   
   numRowsIm, numColsIm, numBandsIm, dataTypeIm = ipcv.dimensions(image)
   
   #Rotated 180 degrees
   if fid2row - 25 < fid1row < fid2row + 25 and fid3col - 25 < fid2col < fid3col + 25 and fid2row < numRowsIm/2 and fid3col < numColsIm/2:
      print 'hello'
      image = numpy.rot90(image, k=2)
      cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
      cv2.imshow('image', image)
      fid1row, fid1col = ipcv.fftCorrelation2(fid1,image)
      fid2row, fid2col = ipcv.fftCorrelation2(fid2,image)
      fid3row, fid3col = ipcv.fftCorrelation2(fid3,image)
   
   
   blankpts = numpy.array([[blank1row,blank1col],[blank2row,blank2col],[blank3row,blank3col]]).astype(numpy.float32)
   #blankpts = numpy.array([blankfid1,blankfid2,blankfid3]).astype(numpy.float32)
   #print blankpts.shape
   fidpts = numpy.array([[fid1row,fid1col],[fid2row,fid2col],[fid3row,fid3col]]).astype(numpy.float32)
   #print fidpts.shape
   M = cv2.getAffineTransform(blankpts,fidpts)
   regIm = cv2.warpAffine(image,M,(numCols,numRows), borderMode = cv2.BORDER_TRANSPARENT)
   
   cv2.namedWindow('rot',cv2.WINDOW_AUTOSIZE)
   cv2.imshow('rot',regIm.astype(numpy.uint8))
   cv2.waitKey()

   cv2.imwrite('new0001.tif', regIm.astype(numpy.uint8))

   return regIm
def fftCorrelation2(fiducial1C, blankSheetC):
   
   numRows, numCols, numBands, dataType = ipcv.dimensions(blankSheetC)
   numRows1, numCols1, numBands1, dataType1 = ipcv.dimensions(fiducial1C)

   if numBands == 3:
      blankSheet = cv2.cvtColor(blankSheetC, cv.CV_BGR2GRAY)
   elif numBands == 1:
      blankSheet = blankSheetC

   if numBands1 == 3:
      fiducial1 = cv2.cvtColor(fiducial1C, cv.CV_BGR2GRAY)
   elif numBands1 == 1:
      fiducial1 = fiducial1C


   freqFid1 = numpy.fft.fft2(fiducial1)
   freqBlank = numpy.fft.fft2(blankSheet)

   magFid1 = numpy.absolute(freqFid1)
   magBlank = numpy.absolute(freqBlank)

   phaseFid1 = numpy.angle(freqFid1)
   phaseBlank = numpy.angle(freqBlank)

   correlation = magBlank * magFid1 * numpy.exp(1j * (phaseBlank - phaseFid1))
 
   corrSpat = numpy.fft.ifft2(correlation)
   corrSpat = numpy.absolute(numpy.fft.fftshift(corrSpat))

   dispCorrSpat = corrSpat / numpy.max(corrSpat)

 #  print dispCorrSpat.max(), dispCorrSpat.min()

  # cv2.namedWindow('corrSpat', cv2.WINDOW_AUTOSIZE)
  # cv2.imshow('corrSpat', dispCorrSpat)
  # cv2.waitKey()

   locationMax = numpy.argmax(corrSpat)
   rowLoc, colLoc = numpy.unravel_index(locationMax, (numRows, numCols))
   displayIm = cv2.merge((blankSheet, blankSheet, blankSheet))

   displayIm[rowLoc - 1:rowLoc+2, colLoc-1:colLoc+2, 2] = 0
   displayIm[rowLoc-1:rowLoc+2, colLoc-1:colLoc+2, 0:1] = 255

  # cv2.namedWindow('displayIm', cv2.WINDOW_AUTOSIZE)
  # cv2.imshow('displayIm', displayIm)
  # cv2.waitKey()
   '''
   fftFid1 = numpy.fft.ifftshift(centerFreqFid1)
   fftBlank = numpy.fft.ifftshift(centerFreqBlank)
   Fid1 = numpy.fft.ifft2(fftFid1)
   Blank = numpy.fft.ifft2(fftBlank)
   '''
   return rowLoc, colLoc
Beispiel #4
0
def circle(blank):
   
   numRows,numCols,numBands, dtype = ipcv.dimensions(blank)
   img = cv2.medianBlur(blank,1)
   cimg = cv2.cvtColor(img,cv.CV_BGR2GRAY)
   img = cv2.cvtColor(img,cv.CV_BGR2GRAY)
   mask = np.zeros((numRows,numCols)).astype(np.uint8)
   mask[690:773,19:105] = 1
   mask[15:100,512:603] = 1
   mask[700:780,490:590] = 1
   img = img*mask

   circles = cv2.HoughCircles(img,cv.CV_HOUGH_GRADIENT,1,40,
                                     param1=50,param2=20,minRadius=7,maxRadius=24)
#   print circles
   '''
   circles = np.uint16(np.around(circles))
   for i in circles[0,:]:
    #  draw the outer circle
      cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
     # draw the center of the circle
      cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

 #     cv2.imwrite('cimg.tif',cimg)
      cv2.imwrite('cimg.tif',cimg)
      cv2.namedWindow('detected circles',cv2.CV_WINDOW_AUTOSIZE)
      cv2.imshow('detected circles',cimg)
      cv2.waitKey(0)
      cv2.destroyAllWindows()
   '''
   return circles      
Beispiel #5
0
def subtraction(newIm, newIm2):      
   #subtracting images
   subtracted = numpy.abs(newIm2 - newIm)
   subtracted = (255 - subtracted)
   numberRows, numberColumns, numberBands, dataType = ipcv.dimensions(subtracted)
  
   return subtracted
Beispiel #6
0
def paddingFid1(answerSheet1, blankSheet1):
   numRowsA, numColsA, numBandsA, dataTypeA = ipcv.dimensions(answerSheet1)
   numRowsB, numColsB, numBandsB, dataTypeB = ipcv.dimensions(blankSheet1)
   if numBandsA == 3:
      answerSheet = cv2.cvtColor(answerSheet1, cv.CV_BGR2GRAY)
   elif numBandsA == 1:
      answerSheet = answerSheet1

   if numBandsB == 3:
      blankSheet = cv2.cvtColor(blankSheet1, cv.CV_BGR2GRAY)
   elif numBandsB == 1:
      blankSheet = blankSheet1
   
   ################FOR LOW RES##################### 
   #Bottom Left Fiducial
   #fiducial1a = blankSheet[717:759,129:171]
   fiducial1a = blankSheet[717:759,38:81]
   
   numRowsF1, numColsF1, numBandsF1, dataTypeF1 = ipcv.dimensions(fiducial1a)

   numRowsAN, numColsAN, numBandsAN, dataTypeAN = ipcv.dimensions(answerSheet)

   print numRowsB, numColsB
   print numRowsAN, numColsAN

   pad_height1 = numpy.absolute(numRowsAN - numRowsF1)/2.0
   pad_width1 = numpy.absolute(numColsAN - numColsF1)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsAN - numRowsF1) % 2 == 0 and (numColsAN - numColsF1) % 2 == 0:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1),(pad_width1, pad_width1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF1) % 2 == 0 and (numColsAN - numColsF1) % 2 != 0:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1),(pad_width1, pad_width1 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF1) %2 != 0 and (numColsAN - numColsF1) % 2 == 0:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1 + 1),(pad_width1, pad_width1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   else:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1 + 1),(pad_width1, pad_width1 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   
   numRowsF, numColsF, numBandsF, dataTypeF = ipcv.dimensions(fiducial1)
   print numRowsF, numColsF
   cv2.imwrite('fiducial1.tif', fiducial1)

   return fiducial1
Beispiel #7
0
def filter_bandreject(img,
                      radialCenter,
                      bandwidth,
                      order=1,
                      filterShape=ipcv.IPCV_IDEAL):
    """
	:purpose:
		generates a bandreject filter
	:inputs:
		img [np.ndarray]
			'--> img to generate filter for
		radialCenter [np.ndarray]
			'--> size of bandpass
		bandwidth [np.ndarray]
			'--> size of bandpass
		order [int]
			'--> order for butterworth filter
		filterShape [int]
			'--> type of filter to apply
	:return:
		frequency filter [np.ndarray]

	"""

    try:
        dims = ipcv.dimensions(img)
        r = dims["rows"]
        c = dims["cols"]
        u = np.arange(r)
        v = np.arange(c)
        u, v = np.meshgrid(u, v)
        D = np.sqrt((u - r / 2)**2 + (v - c / 2)**2)

        if filterShape == ipcv.IPCV_IDEAL:
            D[D < (radialCenter - bandwidth / 2)] = 1
            D[D >= (radialCenter + bandwidth / 2)] = 1
            D[D != 1] = 0

        elif filterShape == ipcv.IPCV_GAUSSIAN:
            xp = -.5 * ((D**2 - radialCenter**2) / (D * bandwidth))**2
            D = 1 - np.exp(xp)
            D = np.clip(D, 0, 1)

        elif filterShape == ipcv.IPCV_BUTTERWORTH:
            denom = 1.0 + ((D * bandwidth) /
                           (D**2 - radialCenter**2))**(2 * order)
            D = 1.0 / denom

        return D

    except Exception as e:
        ipcv.debug(e)
Beispiel #8
0
def filter_notchreject(img, notchCenter, notchRadius, order=1, filterShape=ipcv.IPCV_IDEAL):
	"""
	:purpose:
		generates a notch reject filter
	:inputs:
		img [np.ndarray]
			'--> img to generate filter for
		notchCenter [tuple]
			'--> notch offset
		notchRadius 
			'--> radius of the notch
		filterShape
			'--> type of filter to apply
	:return:
		frequency filter [np.ndarray]

	"""


	try:
		dims = ipcv.dimensions(img)
		r = dims["rows"]
		c = dims["cols"]
		u = np.arange(r)
		v = np.arange(c)
		u, v = np.meshgrid(u, v)

		uCenter = notchCenter[0]
		vCenter = notchCenter[1]

		D1 = np.sqrt( (u-r/2-uCenter)**2 + (v-c/2-vCenter)**2 ) 
		D2 = np.sqrt( (u-r/2+uCenter)**2 + (v-c/2+vCenter)**2 ) 


		if filterShape == ipcv.IPCV_IDEAL:
			H = np.zeros( (r,c) )
			H[D1 <= notchRadius] = 1
			H[D2 <= notchRadius] = 1

		elif filterShape == ipcv.IPCV_GAUSSIAN:
			xp = -.5 * ( (D1 * D2)/(notchRadius**2) )
			H = 1 - np.exp( xp )

		elif filterShape == ipcv.IPCV_BUTTERWORTH:
			denom = 1 + ( (notchRadius**2) / (D1 * D2) )**order
			H = 1 / denom

		return H

	except Exception as e:
		ipcv.debug(e)
def read_in_files2(pdf,blank):

   #convert pdf to tif
  # os.system( "convert " + pdf + " answers_%d.tif")
  # os.system( "convert " + blank + " orig.tif")
   original = cv2.imread('original_300.tif')
   numR, numC, numB, dtype = ipcv.dimensions(original)
   print original.shape
   if numB ==3:
      original = cv2.cvtColor(original,cv.CV_BGR2GRAY)
   
   original[original<=200]=0
   original[original>200]=255
   print original.shape
   cv2.imwrite('original300dpi.tif',original )
   lis = glob.glob('answers_rot*.tif')
   lis = sorted(lis)
   print'lis', lis
   count = 0
   sheets = []
   for im in range(len(lis) ):
      current = lis[im]
      current = cv2.imread(current)
#      numRows, numCols, numBands, dtype = scantron.dimensions(current)
      numRows, numCols, numBands, dtype = ipcv.dimensions(current)
      if numBands ==3:
         im = cv2.cvtColor(current,cv.CV_BGR2GRAY)
      else:
         im = current
      if numpy.average(im) > 230:
         im[im<=200]=0
         im[im>200]=255
         cv2.imwrite('blackDPI%04i.tif' %count,im)
      else:
         cv2.imwrite('blackDPI%04i.tif' %count,im)
      sheets.append(im)
      count = count +1
   return sheets, original
Beispiel #10
0
def paddingFid2(answerSheet1, blankSheet1):
   numRowsA, numColsA, numBandsA, dataTypeA = ipcv.dimensions(answerSheet1)
   numRowsB, numColsB, numBandsB, dataTypeB = ipcv.dimensions(blankSheet1)
   if numBandsA == 3:
      answerSheet = cv2.cvtColor(answerSheet1, cv.CV_BGR2GRAY)
   elif numBandsA == 1:
      answerSheet = answerSheet1

   if numBandsB == 3:
      blankSheet = cv2.cvtColor(blankSheet1, cv.CV_BGR2GRAY)
   elif numBandsB == 1:
      blankSheet = blankSheet1
   
   ################FOR LOW RES##################### 
   #Bottom Right Fiducial
   #fiducial2a = blankSheet[714:762,608:656]
   fiducial2a = blankSheet[714:762,517:567]
   
   numRowsF2, numColsF2, numBandsF2, dataTypeF2 = ipcv.dimensions(fiducial2a)
   
   numRowsAN, numColsAN, numBandsAN, dataTypeAN = ipcv.dimensions(answerSheet)
   
   pad_height2 = numpy.absolute(numRowsAN - numRowsF2)/2.0
   pad_width2 = numpy.absolute(numColsAN - numColsF2)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsAN - numRowsF2) % 2 == 0 and (numColsAN - numColsF2) % 2 == 0:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2),(pad_width2, pad_width2)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF2) % 2 == 0 and (numColsAN - numColsF2) % 2 != 0:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2),(pad_width2, pad_width2 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF2) %2 != 0 and (numColsAN - numColsF2) % 2 == 0:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2 + 1),(pad_width2, pad_width2)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   else:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2 + 1),(pad_width2, pad_width2 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))

   cv2.imwrite('fiducial2.tif', fiducial2)

   return fiducial2
Beispiel #11
0
def rotate(blank, answer):
   numRows, numCols, numBands, dtype = ipcv.dimensions(blank)
   print 'blank:rows,cols', numRows, numCols
   numRowsA, numColsA, numBandsA, dataTypeA = ipcv.dimensions(answer)
   print 'answer:rows,cols', numRowsA, numColsA
   blankPTS = ipcv.circle(blank)
   answerPTS = ipcv.circle(answer)

   blankPTS.shape = (3, 3)
   answerPTS.shape = (3, 3)

   blankPTS = blankPTS[:, 0:2].astype(np.float32)
   answerPTS = answerPTS[:, 0:2].astype(np.float32)

   M = cv2.getAffineTransform(blankPTS, answerPTS)
   image = cv2.warpAffine(answer,M,(numCols,numRows))
   cv2.namedWindow('rotated',cv2.WINDOW_AUTOSIZE)
   cv2.imshow('rotated',image.astype(np.uint8))
   numRowsi, numColsi, numBandsi, dataTypei = ipcv.dimensions(image)
   print 'image:rows,cols:', numRowsi, numColsi
   cv2.waitKey()

   return image
def histogram(im, maxCount=255, ignoreZero=False):
    numberRows, numberColumns, numberBands, dataType = ipcv.dimensions(im)
    histogram = []
    pdf = []
    cdf = []
    for band in range(numberBands):
        h = numpy.int32(
            cv2.calcHist([im], [band], None, [maxCount + 1],
                         [0, maxCount + 1]))
        if ignoreZero:
            h[0, 0] = 0
        histogram.append(h)
        pdf.append(histogram[-1] /
                   numpy.sum(histogram[-1]).astype(numpy.float64))
        cdf.append(numpy.cumsum(pdf[-1]))
    return numpy.asarray(histogram), numpy.asarray(pdf), numpy.asarray(cdf)
Beispiel #13
0
def frequency_filter(im, frequencyFilter, delta=0):
   '''
   title::
      frequency_filter

   description::
      This method applies a frequency filter to the Fourier transform
      of the specified input image. 
      First, the image dimensions are determined. The 2D inverse Fourier
      Transform is taken of the input image, which is then shifted to
      center the zero-frequency component to the center of the array.
      The transform is then multiplied by the frequency filter.
      The result is shifted back and the 2D inverse Fourier transform is 
      taken. These steps are performed for each band in the input image.
      The filtered image is returned as type numpy.complex128. 

   attributes::
      im
         Input source image, of type numpy array
      frequencyFilter
         Mask to be applied to the input image to filter out some
         frequencies and preserve others
      delta
         Bias value added to the filtered image with a default value of 0.          

   returns::
      Filtered image array of type numpy.complex128

   author::
      Victoria Scholl
   '''

   # Find the image dimensions
   imRows, imColumns, imBands, dataType = ipcv.dimensions(im) 
   filteredImage = numpy.zeros((imRows,imColumns,imBands))
   
   for band in range(imBands): 
      imTransform = numpy.fft.fft2(im[:,:,band])
      transformCentered = numpy.fft.fftshift(imTransform)
      filteredTransform = transformCentered * frequencyFilter
      filteredUncentered = numpy.fft.ifftshift(filteredTransform)
      filteredImage[:,:,band] = numpy.fft.ifft2(filteredUncentered)
   
   filteredImage += delta

   return filteredImage.astype(numpy.complex128)
Beispiel #14
0
def fast(src,
         differenceThreshold=50,
         contiguousThreshold=12,
         nonMaximalSuppression=True,
         debug=True):
    img = src.copy()
    circumference = 16
    rollArray = [[-3, 0], [-3, -1], [-2, -2], [-1, -3], [0, -3], [1, -3],
                 [2, -2], [3, -1], [3, 0], [3, 1], [2, 2], [1, 3], [0, 3],
                 [-1, 3], [-2, 2], [-3, 1]]
    dims = ipcv.dimensions(img, 'dict')

    allCorners = np.zeros(img.shape)
    maximaSum = allCorners
    points = np.zeros((dims["rows"], dims["cols"], circumference))
    unchanged = np.zeros((dims["rows"], dims["cols"], circumference))

    for index, rc in enumerate(rollArray):
        points[:, :, index] = np.roll(np.roll(img, rc[0], axis=0),
                                      rc[1],
                                      axis=1)
        unchanged[:, :, index] = img

    greaterThan = (unchanged - points) > differenceThreshold
    lessThan = ((points - unchanged) > differenceThreshold)

    for band in range(circumference):
        posOverlap = greaterThan[:, :, 0:contiguousThreshold] == 1
        negOverlap = lessThan[:, :, 0:contiguousThreshold] == 1
        posCornerCheck = np.sum(posOverlap, axis=2)
        negCornerCheck = np.sum(negOverlap, axis=2)

        allCorners[np.where(posCornerCheck >= contiguousThreshold)] = 1
        allCorners[np.where(negCornerCheck >= contiguousThreshold)] = 1

        maximaSum = maximaSum + allCorners
        greaterThan = np.roll(greaterThan, 1, axis=2)
        lessThan = np.roll(lessThan, 1, axis=2)

    # if nonMaximalSuppression:
    # 	firstDerivative = np.gradient(maximaSum)
    # 	secondDerivative = np.gradient(maximaSum)

    finalCorners = np.clip(allCorners, 0, 1).astype(ipcv.IPCV_8U)
    return finalCorners
Beispiel #15
0
def map_rotation_scale(src, rotation=0, scale=[1, 1]):
    try:
        theta = np.radians(rotation)
        srcDims = ipcv.dimensions(src, returnType="dictionary")

        K = srcDims['cols']
        L = srcDims['rows']

        W = scale[0]
        H = scale[1]
        M = K * W
        N = L * H

        x = K
        y = H

        dimVector = np.asmatrix([x, y, 1])

        # SCALING
        scaleMat = np.asarray([[W, 0, 0], [0, H, 0], [0, 0, 1]])
        dimVector = dimVector * scaleMat

        scaledDims = np.asmatrix(
            [np.arange(dimVector[0, 0]),
             np.arange(dimVector[0, 1]), 1])

        dimVector[0, 0] = dimVector[0, 0] - M / 2
        dimVector[0, 1] = N / 2 - dimVector[0, 1]

        # ROTATION
        sinTheta = np.sin(theta)
        cosTheta = np.cos(theta)
        rotationMat = np.asmatrix([[cosTheta, -sinTheta, 0.0],
                                   [sinTheta, cosTheta, 0.0], [0., 0., 1.0]])
        dimVector = dimVector * rotationMat

        #Realigning Image about corner
        dimVector[0, 0] = dimVector[0, 0] + K / 2
        dimVector[0, 1] = L / 2 - dimVector[0, 1]

        return dimVector[0, 0].astype(IPCV_32F), dimVector[0,
                                                           1].astype(IPCV_32F)

    except Exception as e:
        ipcv.debug(e)
Beispiel #16
0
def filter_lowpass(img, cutoffFrequency, order=1, filterShape=ipcv.IPCV_IDEAL):
    """
	:purpose:
		generates a lowpass filter
	:inputs:
		img [np.ndarray]
			'--> img to generate filter for
		cutoffFrequency [np.ndarray]
			'--> notch offset
		order
			'--> order for butterworth filter
		filterShape
			'--> type of filter to apply
	:return:
		frequency filter [np.ndarray]

	"""

    try:
        dims = ipcv.dimensions(img)
        r = dims["rows"]
        c = dims["cols"]
        u = np.arange(r)
        v = np.arange(c)
        u, v = np.meshgrid(u, v)
        lowPass = np.sqrt((u - r / 2)**2 + (v - c / 2)**2)

        if filterShape == ipcv.IPCV_IDEAL:
            lowPass[lowPass <= cutoffFrequency] = 1
            lowPass[lowPass >= cutoffFrequency] = 0

        elif filterShape == ipcv.IPCV_GAUSSIAN:
            xp = -1 * (lowPass**2) / (2 * cutoffFrequency**2)
            lowPass = np.exp(xp)
            lowPass = np.clip(lowPass, 0, 1)

        elif filterShape == ipcv.IPCV_BUTTERWORTH:
            denom = 1.0 + (lowPass / cutoffFrequency)**(2 * order)
            lowPass = 1.0 / denom

        return lowPass

    except Exception as e:
        ipcv.debug(e)
Beispiel #17
0
def scan_main(pdf,original):
   answerSheets, blankSheet1 = ipcv.read_in_files(pdf,original)
   numRowsO, numColsO, numBandsO, dataTypeO = ipcv.dimensions(blankSheet1)
   regIm = numpy.zeros((numRowsO,numColsO))
   x = 0
   for answer in range(len(answerSheets)):
      print 'x', x
      answerSheet1 = numpy.asarray(answerSheets)
      blankSheet1 = numpy.asarray(blankSheet1)

      answerSheet = answerSheet1[answer]
      blankSheet = blankSheet1
      blankSheet2 = cv2.imread('paddedBlank.tif')

      fiducial1  = ipcv.paddingFid1(answerSheet, blankSheet)
      fiducial2  = ipcv.paddingFid2(answerSheet, blankSheet)
      fiducial3  = ipcv.paddingFid3(answerSheet, blankSheet)
   
      #Find points for the centers of the fiducials in the blank sheets
      blank1row, blank1col = ipcv.fftCorrelation2(fiducial1,blankSheet)
      blank2row, blank2col = ipcv.fftCorrelation2(fiducial2,blankSheet)
      blank3row, blank3col = ipcv.fftCorrelation2(fiducial3,blankSheet)

      #Find points for the centers of the fiducials in the answer sheets
      fid1row, fid1col = ipcv.fftCorrelation2(fiducial1,answerSheet)
      fid2row, fid2col = ipcv.fftCorrelation2(fiducial2,answerSheet)
      fid3row, fid3col = ipcv.fftCorrelation2(fiducial3,answerSheet)
  
      #Rotate, translate, and Scale
      regIm = ipcv.register(fid1row, fid1col, fid2row, fid2col, fid3row, fid3col, blank1row, blank1col, blank2row, blank2col, blank3row, blank3col, answerSheet, blankSheet)

      #blank = cv2.imread('paddedBlank.tif')
      #Get info
      firstName, lastName, UID, additional = ipcv.read_info(blankSheet2, regIm)
      #Grading
      newIm = ipcv.grading(regIm)
      newIm2 = ipcv.answers(regIm)
      subtracted = ipcv.subtraction(newIm, newIm2)
      count = ipcv.convolution(subtracted, threshold = .9)
      percent = ipcv.finalGrade(count)
      x = x+1
      
   return percent
Beispiel #18
0
def frequency_filter(img, frequencyFilter, delta=0):
    """
	:purpose:
		applies a frequency filter to an image
	:inputs:
		img [np.ndarray]
			'--> image to be filtered
		frequencyFilter [np.ndarray]
			'--> filter to apply to image
		delta [int]
			'--> offset to be added to image at the end
	:return:
		filtered image
	"""
    try:
        #generating deep copy
        img = img.copy()
        rows, cols, bands, _ = ipcv.dimensions(img, 't')
        #preparing freq and filter arrays
        freqFiltered = np.zeros((rows, cols, bands)).astype(ipcv.IPCV_128C)
        spatialFiltered = np.zeros((rows, cols, bands)).astype(ipcv.IPCV_128C)
        x, y = np.indices((rows, cols))
        shifter = (-1)**(x + y)

        #making image 3D if necessary for computational ese
        if len(img.shape) == 2:
            img = img.reshape((rows, cols, 1))

        for band in range(bands):
            #shifting image band by band
            spatial = (img[:, :, band] * shifter).copy()
            fft = np.fft.fft2(spatial)
            #applying frequency filter
            freqFiltered[:, :, band] = fft * frequencyFilter
            spatialFiltered[:, :, band] = np.abs(
                np.fft.ifft2(freqFiltered[:, :, band])) * shifter

        return (spatialFiltered + delta)

    except Exception as e:
        ipcv.debug(e)
Beispiel #19
0
def frequency_filter(img, frequencyFilter, delta=0):
    try:
        rows, cols, bands, _ = ipcv.dimensions(img, 't')
        freqFiltered = np.zeros((rows, cols, bands))
        x, y = np.indices((rows, cols))
        shifter = np.dstack(
            ((-1)**(x + y), ) * bands) if bands > 1 else (-1)**(x + y)
        src = img.copy() * shifter

        fft = np.fft.fft2(src)
        frequencyFilter = np.dstack(
            (frequencyFilter, ) * bands) if bands > 1 else frequencyFilter
        freqFiltered = fft * frequencyFilter

        spatialFiltered = np.abs(np.fft.ifft2(freqFiltered))
        spatialFiltered = shifter * spatialFiltered

        return (spatialFiltered + delta).astype(ipcv.IPCV_8U)

    except Exception as e:
        ipcv.debug(e)
def paddingFiducials(answerSheet1, blankSheet1):
   numRowsA, numColsA, numBandsA, dataTypeA = ipcv.dimensions(answerSheet1)
   numRowsB, numColsB, numBandsB, dataTypeB = ipcv.dimensions(blankSheet1)
   print numRowsB, numColsB
   if numBandsA == 3:
      answerSheet = cv2.cvtColor(answerSheet1, cv.CV_BGR2GRAY)
   elif numBandsA == 1:
      answerSheet = answerSheet1

   if numBandsB == 3:
      blankSheet = cv2.cvtColor(blankSheet1, cv.CV_BGR2GRAY)
   elif numBandsB == 1:
      blankSheet = blankSheet1

   ################FOR HIGH RES####################
   #Bottom Left Fiducial
   #fiducial1a = blankSheet[2993:3162,167:337]
   #Bottom Right Fiducial
   #fiducial2a = blankSheet[2980:3174,2163:2356]
   #Top Right Fiducial
   #fiducial3a = blankSheet[120:323,2214:2416]
   
   ################FOR LOW RES##################### 
   #Bottom Left Fiducial
   fiducial1a = blankSheet[717:759,38:81]
   #Bottom Right Fiducial
   fiducial2a = blankSheet[714:762,517:567]
   #Top Right Fiducial
   fiducial3a = blankSheet[29:78,531:579]
   
   numRowsF1, numColsF1, numBandsF1, dataTypeF1 = ipcv.dimensions(fiducial1a)
   numRowsF2, numColsF2, numBandsF2, dataTypeF2 = ipcv.dimensions(fiducial2a)
   numRowsF3, numColsF3, numBandsF3, dataTypeF3 = ipcv.dimensions(fiducial3a)
   print numRowsF1, numColsF1

   pad = numpy.absolute(numRowsA - numColsA)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsA-numColsA) % 2 != 0:
      answerSheet = numpy.pad(answerSheet, ((0,0),(pad,pad+1)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsA-numColsA) % 2 == 0:
      answerSheet = numpy.pad(answerSheet, ((0,0),(pad,pad)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))

   numRowsAN, numColsAN, numBandsAN, dataTypeAN = ipcv.dimensions(answerSheet)

   pad_height1 = numpy.absolute(numRowsAN - numRowsF1)/2.0
   pad_width1 = numpy.absolute(numColsAN - numColsF1)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsAN - numRowsF1) % 2 == 0 and (numColsAN - numColsF1) % 2 == 0:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1),(pad_width1, pad_width1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF1) % 2 == 0 and (numColsAN - numColsF1) % 2 != 0:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1),(pad_width1, pad_width1 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF1) %2 != 0 and (numColsAN - numColsF1) % 2 == 0:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1 + 1),(pad_width1, pad_width1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   else:
      fiducial1 = numpy.pad(fiducial1a,((pad_height1, pad_height1 + 1),(pad_width1, pad_width1 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   print 'fiducial1 shape:', fiducial1.shape
   print 'answerSheet shape:', answerSheet.shape

   pad_height2 = numpy.absolute(numRowsAN - numRowsF2)/2.0
   pad_width2 = numpy.absolute(numColsAN - numColsF2)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsAN - numRowsF2) % 2 == 0 and (numColsAN - numColsF2) % 2 == 0:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2),(pad_width2, pad_width2)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF2) % 2 == 0 and (numColsAN - numColsF2) % 2 != 0:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2),(pad_width2, pad_width2 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF2) %2 != 0 and (numColsAN - numColsF2) % 2 == 0:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2 + 1),(pad_width2, pad_width2)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   else:
      fiducial2 = numpy.pad(fiducial2a,((pad_height2, pad_height2 + 1),(pad_width2, pad_width2 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   print 'fiducial2 shape:', fiducial2.shape
   print 'answerSheet shape:', answerSheet.shape

   pad_height3 = numpy.absolute(numRowsAN - numRowsF3)/2.0
   pad_width3 = numpy.absolute(numColsAN - numColsF3)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsAN - numRowsF3) % 2 == 0 and (numColsAN - numColsF3) % 2 == 0:
      fiducial3 = numpy.pad(fiducial3a,((pad_height3, pad_height3),(pad_width3, pad_width3)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF3) % 2 == 0 and (numColsAN - numColsF3) % 2 != 0:
      fiducial3 = numpy.pad(fiducial3a,((pad_height3, pad_height3),(pad_width3, pad_width3 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsAN - numRowsF3) %2 != 0 and (numColsAN - numColsF3) % 2 == 0:
      fiducial3 = numpy.pad(fiducial3a,((pad_height3, pad_height3 + 1),(pad_width3, pad_width3)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   else:
      fiducial3 = numpy.pad(fiducial3a,((pad_height3, pad_height3 + 1),(pad_width3, pad_width3 + 1)), 'constant', constant_values = ((maxCount, maxCount),(maxCount,maxCount)))
   print 'fiducial3 shape:', fiducial3.shape
   print 'answerSheet shape:', answerSheet.shape

   pad1 = numpy.absolute(numRowsB - numColsB)/2.0
   maxCount = numpy.max(blankSheet)

   if (numRowsB-numColsB) % 2 != 0:
      blankSheet = numpy.pad(blankSheet, ((0,0),(pad1,pad1+1)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))
   elif (numRowsA-numColsA) % 2 == 0:
      blankSheet = numpy.pad(blankSheet, ((0,0),(pad1,pad1)), 'constant', constant_values=((maxCount, maxCount),(maxCount,maxCount)))

   #cv2.imwrite('paddedBlank.tif', blankSheet)
   fiducials = numpy.dstack([fiducial1, fiducial2, fiducial3])
   print fiducials.shape

   return fiducials, answerSheet, blankSheet
def filter_notchreject(im, notchCenter, notchRadius, order=1, filterShape=ipcv.IPCV_IDEAL):

   '''
   title::
      filter_notchreject

   description::
      This method creates a frequency filter that rejects
      specific frequencies supplied by the user.
      User must specify the coordinates of the frequencies to be blocked 
      (in the form of a list of tuples (u,v)), each with a corresponding
      radius value (in the list, notchRadius)
      A mask is created to preserve the other frequencies in the image.
      First, the dimensions of the input image are determined.
      Then an array of ones is created with the same dimensions to serve 
      as the notchreject filter. 
      The dist method is used to return a distance value at each pixel
      location (measured from the corner of the image). This dist filter
      is then rolled twice in both the x and y dimensions to center the 
      values about the center of the array. 
      The specified filter shape is then created based on the use's input. 
      The filter is returned as type numpy.float64. The filter is ready to be 
      multiplied with a centered fourier transform of the input image.

   attributes::
      im
         Input image of tpye numpy nd array, used to get the dimensions for
         the frequency filter.
      notchCenter
        List of tuples with coordinates (u,v) corresponding to frequencies
        in the fourier transform to be rejected. 
      notchRadius
        The size of the notch to be created at each (u,v) coordinate. 
      order
         Integer value that influences the shape of the butterworth filter. 
         The higher the order, the more the butterworth filter resembles an 
         ideal filter. 
      filterShape
         Options for the shape of the filter, specified in the constants.py 
         file in the ipcv directory. The different shapes will attenuate 
         the frequencies differently. 
            IDEAL
               Ideal shaped filter STRICTLY blocks ALL frequencies within the
               specified notch sizes and locations. Binary mask. 
            BUTTERWORTH
               Gaussian-like shaped filter that can be tuned based on the order
               parameter. 
            GAUSSIAN
               Gaussian-shaped filter. 
   returns::
      notchreject filter - numpy array with the same dimensions as the input image
      that will preserve all frequencies outside of the specified notches.

   author::
      Victoria Scholl
   '''

   # get image dimensions, which dictate the filter dimensions
   imRows, imColumns, imBands, dataType = ipcv.dimensions(im)
   notchRejectFilter = numpy.ones([imRows,imColumns])

   # use ipcv.dist to generate an array with distances from the corner pixel.
   # roll twice to center the array (distances measured from center) 
   distFilter = ipcv.dist( ( imRows, imColumns ) )
   distFilter = numpy.roll(numpy.roll(distFilter, imRows/2, axis=0), imColumns/2, axis=1)

   for center in range(len(notchCenter)):
      # D1 is the distance from the notch
      # D2 is the distance from the notch's conjugate 
      D1 = numpy.roll(numpy.roll(distFilter,imRows/2 - notchCenter[center][0],axis=1),imColumns/2-notchCenter[center][1],axis=0)
      D2 = numpy.roll(numpy.roll(distFilter,imRows/2 + notchCenter[center][0],axis=1),imColumns/2+notchCenter[center][1],axis=0)
     

      if filterShape == ipcv.IPCV_IDEAL:
         notchRejectFilter[ D1 <= notchRadius[center] ] = 0
         notchRejectFilter[ D2 <= notchRadius[center] ] = 0

      elif filterShape == ipcv.IPCV_BUTTERWORTH:  # butterworth equation
         
         # To avoid a div by 0 error
         productOfDs = D1 * D2
         productOfDs[productOfDs == 0] == 1e-10


         nextNotchRejectFilter = 1 / ( 1 + (( notchRadius[center]**2 ) / (productOfDs)) ** order) 
         notchRejectFilter = notchRejectFilter * nextNotchRejectFilter

      else: # Third filter type option is Gaussian
         nextNotchRejectFilter = 1 - numpy.exp( -0.5 * (D1 * D2) / ( notchRadius[center]**2) )
         notchRejectFilter = notchRejectFilter * nextNotchRejectFilter

   notchRejectFilter = numpy.roll(numpy.roll(notchRejectFilter, imRows/2, axis=0), imColumns/2, axis=1)
   
   return notchRejectFilter.astype(numpy.float64)
Beispiel #22
0
def filter_lowpass(im, cutoffFrequency, order=1, filterShape=ipcv.IPCV_IDEAL):

   '''
   title::
      filter_lowpass

   description::
      This method creates a lowpass filter to be applied to the 
      centered fourier transform of the input image.
      First, the dimensions of the input image are determined.
      Then an array of zeros is created with the same dimensions to serve 
      as the lowpass filter. 
      The dist method is used to return a distance value at each pixel
      location (measured from the corner of the image). This dist filter
      is then rolled twice in both the x and y dimensions to center the 
      values about the center of the array. 
      The specified filter shape is then created based on the use's input. 
      The filter is returned as type numpy.float64; ready to be applied to
      the input image using the frequency_filter.py method. 

   attributes::
      im
         Input image of tpye numpy nd array, used to get the dimensions for
         the frequency filter.
      cutoffFrequency
         Frequency of type integer above which to attentuate higher frequencies
         (frequencies lower than the cutoff value will be preserved). 
      order
         Integer value that influences the shape of the butterworth filter. 
         The higher the order, the more the butterworth filter resembles an 
         ideal filter. 
      filterShape
         Options for the shape of the filter, specified in the constants.py 
         file in the ipcv directory. The different shapes will attenuate 
         the higher frequencies differently. 
            IDEAL
               Ideal shaped filter STRICTLY blocks ALL frequencies greater than
               the cutoffFrequency. Binary mask. 
            BUTTERWORTH
               Gaussian-like shaped filter that can be tuned based on the order
               parameter. 
            GAUSSIAN
               Gaussian-shaped filter. 
   returns::
      lowpass filter - numpy array with the same dimensions as the input image

   author::
      Victoria Scholl

   '''

   # get image dimensions, which dictate the filter dimensions
   imRows, imColumns, imBands, dataType = ipcv.dimensions(im)
   lowPassFilter = numpy.zeros([imRows,imColumns])

   # use ipcv.dist to generate an array with distances from the corner pixel.
   # roll twice to center the array (distances measured from center) 
   distFilter = ipcv.dist( ( imRows, imColumns ) )
   distFilter = numpy.roll(numpy.roll(distFilter, imRows/2, axis=0), 
                           imColumns/2, axis=1)


   if filterShape == ipcv.IPCV_IDEAL:
      # threshold dist array. distances < cutoff freq set to 1, else to 0. 
      lowPassFilter[ distFilter <= cutoffFrequency ] = 1
      lowPassFilter[ distFilter > cutoffFrequency ] = 0

   elif filterShape == ipcv.IPCV_BUTTERWORTH:  # butterworth equation
      lowPassFilter = 1 / ( 1 + (( distFilter/cutoffFrequency)**(2*order)))

   else: # Third filter type option is Gaussian
      lowPassFilter = numpy.exp(-1*(distFilter**2)/(2.0*cutoffFrequency**2))

   return lowPassFilter.astype(numpy.float64)
def fftCorrelation(fiducial1C, fiducial2C, fiducial3C, blankSheetC):
   
   numRows, numCols, numBands, dataType = ipcv.dimensions(blankSheetC)
   numRows1, numCols1, numBands1, dataType1 = ipcv.dimensions(fiducial1C)
   numRows2, numCols2, numBands2, dataType2 = ipcv.dimensions(fiducial2C)
   numRows3, numCols3, numBands3, dataType3 = ipcv.dimensions(fiducial3C)
   print 'blank bands:', numBands
   print 'fiducial1 bands:', numBands1
   print 'fiducial2 bands:', numBands2
   print 'fiducial3 bands:', numBands3

   if numBands == 3:
      blankSheet = cv2.cvtColor(blankSheetC, cv.CV_BGR2GRAY)
   elif numBands == 1:
      blankSheet = blankSheetC

   if numBands1 == 3:
      fiducial1 = cv2.cvtColor(fiducial1C, cv.CV_BGR2GRAY)
   elif numBands2 == 1:
      fiducial1 = fiducial1C

   if numBands2 == 3:
      fiducial2 = cv2.cvtColor(fiducial2C, cv.CV_BGR2GRAY)
   elif numBands2 == 1:
      fiducial2 = fiducial2C

   if numBands3 == 3:
      fiducial3 = cv2.cvtColor(fiducial3C, cv.CV_BGR2GRAY)
   elif numBands3 == 1:
      fiducial3 = fiducial3C

   freqFid1 = numpy.fft.fft2(fiducial3)
   freqBlank = numpy.fft.fft2(blankSheet)

   freqFid1 = numpy.fft.fftshift(freqFid1)
   freqBlank = numpy.fft.fftshift(freqBlank)

   magFid1 = numpy.absolute(freqFid1)
   magBlank = numpy.absolute(freqBlank)

   #Takes the log of the magnitude frequency image in order to diplay it
   logMagnitude = numpy.log10(magFid1)
   #Scales the image in order to display
   scaledIm = logMagnitude/numpy.max(logMagnitude)
   scaledIm2 = scaledIm * 255
   intScaledIm2 = scaledIm2.astype(numpy.uint8)
   cv2.namedWindow('fftFiducial', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('fftFiducial', intScaledIm2)
   cv2.waitKey()
   cv2.imwrite('fftFiducial.tif', intScaledIm2)

   #Takes the log of the magnitude frequency image in order to diplay it
   logMagnitude1 = numpy.log10(magBlank)
   #Scales the image in order to display
   scaledIm1 = logMagnitude/numpy.max(logMagnitude1)
   scaledIm21 = scaledIm1 * 255
   intScaledIm21 = scaledIm21.astype(numpy.uint8)
   cv2.namedWindow('fftBlank', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('fftBlank', intScaledIm21)
   cv2.waitKey()
   cv2.imwrite('fftBlank.tif', intScaledIm21)

   phaseFid1 = numpy.angle(freqFid1)
   phaseBlank = numpy.angle(freqBlank)

   correlation = magBlank * magFid1 * numpy.exp(1j * (phaseBlank - phaseFid1))
 
   corrSpat = numpy.fft.ifft2(correlation)
   corrSpat = numpy.absolute(numpy.fft.fftshift(corrSpat))

   dispCorrSpat = corrSpat / numpy.max(corrSpat)

   print dispCorrSpat.max(), dispCorrSpat.min()

   cv2.namedWindow('corrSpat', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('corrSpat', dispCorrSpat)
   cv2.waitKey()

   locationMax = numpy.argmax(corrSpat)
   rowLoc, colLoc = numpy.unravel_index(locationMax, (numRows, numCols))
   displayIm = cv2.merge((blankSheet, blankSheet, blankSheet))
   print rowLoc, colLoc

   displayIm[rowLoc - 2:rowLoc+3, colLoc-2:colLoc+3, 2] = 0
   displayIm[rowLoc-2:rowLoc+3, colLoc-2:colLoc+3, 0:1] = 255

   cv2.namedWindow('displayIm', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('displayIm', displayIm)
   cv2.waitKey()
   cv2.imwrite('dotsFid3.tif', displayIm)
   '''
   fftFid1 = numpy.fft.ifftshift(centerFreqFid1)
   fftBlank = numpy.fft.ifftshift(centerFreqBlank)
   Fid1 = numpy.fft.ifft2(fftFid1)
   Blank = numpy.fft.ifft2(fftBlank)
   '''
   return rowLoc, colLoc
def histogram_enhancement(im, etype='linear2', target=None, maxCount=255):
	"""
	Title: histogram_enhancement
	Author: Molly Hill, [email protected]
	Description:
		Returns given image quantized at set number of levels, using either a uniform or IGS method.
	Attributes:
		im - ndarray, can be grayscale or color of any size
		etype - enhancement type, of the following options:
			    - 'linearX' where X is an integer percent of the area to be
			       clipped/crushed with contrast increas
			    - 'match' where the image is to be matched to a provided
			       target image or PDF
			    - 'equalize' where the image's histogram is to be spread
			       equally across digital count
		target - if etype = 'match', then target must be provided as either an
			 image (3D array) or PDF (1D array)
		maxCount - maximum code value of pixel; must be positive integer
	Requires:
		histogram.py, author: Carl Salvaggio
		dimensions.py, author: Carl Salvaggio
	"""

	if maxCount <= 0 or type(maxCount) is not int:
		msg = "Specified maximum digital count must be a positive integer."
		raise ValueError(msg)
	if type(im) is not numpy.ndarray:
		msg = "Specified image type must be ndarray."
		raise TypeError(msg)
	if etype[:6] != 'linear' and etype != 'match' and etype != 'equalize':
		msg = "Enhancement types available are linear, match, and equalize. Defaulting to linear2."
		print(msg)
	if etype == 'match':
		if type(target) == None:
			etype = 'equalize'
			msg = "If using match, target must be provided."
			print(msg)
		elif target.ndim !=1 and target.ndim !=2:
			print(target.ndim)
			msg = "Provided target must be PDF (1-D array) or image (3-D array)"
			raise TypeError(msg)

	enhIm = numpy.copy(im)
	srcCDF = ipcv.histogram(enhIm)[2]
	DCout = []
	tgtCDF = []
	tgtPDF = target
	
	if etype == 'match' or etype == 'equalize':
		if etype == 'match' and target.ndim != 1: #is image
			tgtCDF = ipcv.histogram(target)[2][0] #create CDF of target, currently does red channel if color
		else: #equalize or PDF passed in as target for matching
			if etype == 'equalize':
				tgtPDF = numpy.ones(maxCount+1)/(maxCount+1)
			tgtCDF = numpy.cumsum(tgtPDF) #convert PDF to CDF

		for i in range(ipcv.dimensions(srcCDF)[1]): #createLUT
			difference = numpy.fabs(numpy.subtract(tgtCDF,srcCDF[0][i])) #red channel only
			DCout.extend([int(maxCount*tgtCDF[numpy.argmin(difference)])])
		for j in range(im.size): #apply LUT
			enhIm.flat[j] = DCout[enhIm.flat[j]] #uses original code value to assign new output from LUT

	else: #linear
		pct = (int(etype[6:])/2) / 100 #extract percent from etype and halve
		difference = numpy.fabs(numpy.subtract(srcCDF[0],pct))
		DCmin = numpy.argmin(difference)
		difference = numpy.fabs(numpy.subtract(srcCDF[0],(1-pct)))
		DCmax = numpy.argmin(difference)

		slope = (maxCount+1)/(DCmax-DCmin)
		intercept = -slope * DCmin
		
		for j in range(enhIm.size):
			px = enhIm.flat[j]
			if px >= DCmax:
				px = maxCount
			elif px <= DCmin:
				px = 0
			else:
				px = slope * px + intercept
			enhIm.flat[j] = int(px)

	return enhIm
Beispiel #25
0
def convolution(subtracted, threshold = .9): 
   numberRows, numberColumns, numberBands, dataType = ipcv.dimensions(subtracted)

   answerRegion = numpy.zeros((300, 60))
   kernel = numpy.zeros((12,12))
   neighborhood = numpy.ones((12, 60))
     
   answerRegion = answerRegion * 1.0
   kernel = kernel * 1.0
   
   answerRegion = subtracted[numberRows-407:numberRows-107, numberColumns-540:numberColumns-480]
   cv2.imshow('region', answerRegion)
   
   numberRowsR, numberColumnsR, numberBandsR, dataType = ipcv.dimensions(answerRegion)
   
   if numberBandsR == 3:
      answerRegion = cv2.cvtColor(answerRegion,cv.CV_BGR2GRAY)

   answerRegion[answerRegion <= 200] = 0
   answerRegion[answerRegion > 200] = 255
   
   count = 0
   #cv2.namedWindow('hood', cv2.WINDOW_AUTOSIZE)
   #for row in range(numberRowsR):
   for row in range(25):
      row = row * 12
      neighborhood = answerRegion[row : row + 12, 0:numberColumnsR]
      #cv2.imshow('hood', neighborhood)
      #cv2.waitKey(300)
      #print neighborhood.shape
      if numpy.mean(neighborhood) >= 254:
	 count = count + 1
         #print count
      else:
         count = count + 0
      row = row + 12           
   #print count
   count1 = count
   
   #column 2
   answerRegion = subtracted[numberRows-407:numberRows-107, numberColumns-464:numberColumns-404]
   cv2.imshow('region', answerRegion)
   cv2.waitKey()
   
   numberRowsR, numberColumnsR, numberBandsR, dataType = ipcv.dimensions(answerRegion)
   
   if numberBandsR == 3:
      answerRegion = cv2.cvtColor(answerRegion,cv.CV_BGR2GRAY)

   answerRegion[answerRegion <= 200] = 0
   answerRegion[answerRegion > 200] = 255
   
   count = 0
   #cv2.namedWindow('hood', cv2.WINDOW_AUTOSIZE)
   for row in range(25):
      row = row * 12
      neighborhood = answerRegion[row : row + 12, 0:numberColumnsR]
      #cv2.imshow('hood', neighborhood)
      #cv2.waitKey(300)
      #print neighborhood.shape
      if numpy.mean(neighborhood) >= 254:
	 count = count + 1
         #print count
      else:
         count = count + 0
      row = row + 12          
   #print count
   count2 = count
   
   count = count1 + count2 
   #print count
   
   return count    
Beispiel #26
0
def answers(key):      
   #ANSWER KEY

   numberRows, numberColumns, numberBands, dataType = ipcv.dimensions(key)
   
   neighborhood = numpy.zeros((12, 12))

   #For questions 1-25 (first column)
   column = 72
   newIm2 = key
   for answer in range(5): 
      row = 385 
      for question in range(25):
         neighborhood = key[row : row + 12, column : column + 12]
         if numpy.mean(neighborhood) < 190:
	    newIm2[row : row + 12, column : column + 12] = 0
	 else:
	    newIm2[row : row + 12, column : column + 12] = 255
         row = row + 12
      column = column + 12  

   #For questions 26-50 (second column) 
   column = 148
   newIm2 = key
   for answer in range(5): 
      row = 385 
      for question in range(25):
         neighborhood = key[row : row + 12, column : column + 12]
         if numpy.mean(neighborhood) < 190:
	    newIm2[row : row + 12, column : column + 12] = 0
	 else:
	    newIm2[row : row + 12, column : column + 12] = 255
         row = row + 12
      column = column + 12 	     
	      
   #For questions 51-75 (third column) 
   column = 225
   newIm2 = key
   for answer in range(5): 
      row = 385 
      for question in range(25):
         neighborhood = key[row : row + 12, column : column + 12]
         if numpy.mean(neighborhood) < 190:
	    newIm2[row : row + 12, column : column + 12] = 0
	 else:
	    newIm2[row : row + 12, column : column + 12] = 255
         row = row + 12
      column = column + 12    
      
   #For questions 76-100 (fourth column) 
   column = 305
   newIm2 = key
   for answer in range(5): 
      row = 385 
      for question in range(25):
         neighborhood = key[row : row + 12, column : column + 12]
         if numpy.mean(neighborhood) < 190:
	    newIm2[row : row + 12, column : column + 12] = 0
	 else:
	    newIm2[row : row + 12, column : column + 12] = 255
         row = row + 12
      column = column + 12   
      
   #For questions 101-125 (fifth column) 
   column = 385
   newIm2 = key
   for answer in range(5): 
      row = 385 
      for question in range(25):
         neighborhood = key[row : row + 12, column : column + 12]
         if numpy.mean(neighborhood) < 190:
	    newIm2[row : row + 12, column : column + 12] = 0
	 else:
	    newIm2[row : row + 12, column : column + 12] = 255
         row = row + 12
      column = column + 12     
      
   #For questions 125-150 (last column) 
   column = 465
   newIm2 = key
   for answer in range(5): 
      row = 385 
      for question in range(25):
         neighborhood = key[row : row + 12, column : column + 12]
         if numpy.mean(neighborhood) < 190:
	    newIm2[row : row + 12, column : column + 12] = 0
	 else:
	    newIm2[row : row + 12, column : column + 12] = 255
         row = row + 12
      column = column + 12      
   return newIm2
Beispiel #27
0
def read_info(sheets, original):
#   original = cv2.cvtColor(original,cv.CV_BGR2GRAY)
#   sheets = cv2.cvtColor(sheets,cv.CV_BGR2GRAY)
   
   hood = numpy.ones((12,12))
   numRows, numCols, numBands, dtype = ipcv.dimensions(original)
#   original = numpy.absolute(original - sheets)
#   cv2.namedWindow('orig',cv2.WINDOW_AUTOSIZE)
#   cv2.imshow('orig', original)
#   cv2.waitKey()
   lastName = []
   hcol = 12
   hrow = 12 
   col = 72
 #  col =162 
   cv2.namedWindow('hood')
   letter = numpy.zeros((26,1))
   for C in range(11):
      row = 51
      for L  in range(26):
         hood = original[row:row + hrow,col:col +hcol]
         if numpy.mean(hood) < 185:
            total = 0
         else:
            total = 255
        # print 'total', total
#         total = numpy.sum(hood)
         letter[L] = total
         row = row +hrow
         if L == 6:
            row = row-1
       #  print 'row',row
       #  cv2.imshow('hood',hood)
       #  cv2.waitKey(600)
      val = (letter[numpy.argmin(letter)])
      #val = (letter[numpy.argmin(letter)])
      #print 'lastval',val
      mean = numpy.mean(letter)
      #print 'mean', mean
      #if mean - 1 < val < mean + 1:
      if val > 0:
      #if mean - 9000 < val < mean + 9000:
    #  if mean - 5900 < val < mean + 5900:
         lastName.append(chr(32))
         
      else:
         lastName.append(chr(numpy.argmin(letter)+65))
      col = col + hcol 
   print 'lastname',lastName
   
   '''
   hood = numpy.ones((9,10))
   numRows, numCols, numBands, dtype = ipcv.dimensions(original)
#   original = numpy.absolute(original - sheets)
#   cv2.namedWindow('orig',cv2.WINDOW_AUTOSIZE)
#   cv2.imshow('orig', original)
#   cv2.waitKey()
   lastName = []
   drow = 3
   dcol = 2
   hcol = 10
   hrow = 9
  # col = 72
   col =162 
   cv2.namedWindow('hood')
   letter = numpy.zeros((26,1))
   for C in range(11):
      row = 51
      for L  in range(26):
         hood = original[row:row + hrow,col:col +hcol]
       #  print 'hood', numpy.mean(hood)
        # if numpy.mean(hood) < 180:
 #        im,threshold = ipcv.otsu_threshold(hood,255, verbose=False)
         #print 'thresh', threshold
#         if numpy.mean(hood) < threshold:
#            total = 0
#         else:
#            total = 255
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
         if L == 6:
            row = row-1
       #  print 'row',row
       #  cv2.imshow('hood',hood)
       #  cv2.waitKey(600)
      val = (letter[numpy.argmin(letter)])
      val = (letter[numpy.argmin(letter)])
      print 'lastval',val
      mean = numpy.mean(letter)
      print 'mean', mean
     # if mean - 3 < val < mean + 3:
      #if mean - 9000 < val < mean + 9000:
      if mean - 5900 < val < mean + 5900:
         lastName.append(chr(32))
         
      else:
         lastName.append(chr(numpy.argmin(letter)+65))
      col = col + hcol + dcol
   print 'lastname',lastName
  # print 'letter', letter
  # print 'row',row
  # print 'col',col
   
   '''
   hood = numpy.ones((9,10))
   firstName = [] 
   drow = 3
   dcol = 2
   hcol = 10
   hrow = 9
#   hcol = 12
#   hrow = 12
   col = 235
   cv2.namedWindow('hood')
   letter = numpy.zeros((26,1))
   for C in range(9):
      row = 51
      for L  in range(26):
         hood = original[row:row + hrow,col:col +hcol]
#       #  if numpy.mean(hood) < 185:
#         if (numpy.mean(hood)< 175 and numpy.mean(hood) <185):
#      #   if numpy.mean(hood) < 175:
#            total = 0
#         else:
#            total = 255
         total = numpy.sum(hood)
         letter[L] = total
#         row = row +hrow
         row = row +hrow + drow
         if L == 6:
            row = row-1
         #cv2.imshow('hood',hood)
#         cv2.waitKey(600)
      val = (letter[numpy.argmin(letter)])
      #print 'location', numpy.argmin(letter)
      #print 'firstval',val
      mean = numpy.mean(letter)
 #     print'mean', mean
      if mean - 9000 < val < mean + 9000:
#      if val > 0:
         firstName.append(chr(32))
     
         
      else:
         firstName.append(chr(numpy.argmin(letter)+65))
#      col = col + hcol 
      col = col + hcol + dcol
   print 'firstname',firstName
   
   
  # UID = numpy.zeros((9))
   UID = []
   drow = 3
   dcol = 2
   hcol = 10
   hrow = 9
   col = 370
   cv2.namedWindow('hood')
   letter = numpy.zeros((10,1))
   for C in range(9):
      row = 51
      for L  in range(10):
         hood = original[row:row + hrow,col:col +hcol]
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
         if L == 6:
            row = row-1
      mean = numpy.mean(letter)
      val = (letter[numpy.argmin(letter)])
      if mean - 5000 < val < mean + 5000:
         UID.append(chr(32))
      else:
         UID.append(numpy.argmin(letter))
     # UID[C] = numpy.argmax(letter)
      col = col + hcol + dcol
   
   print 'UID',UID
   
   #additional = numpy.zeros((9))
   additional = []
   drow = 3
   dcol = 2
   hcol = 10
   hrow = 9
   col = 370
   #cv2.namedWindow('hood')
   letter = numpy.zeros((10,1))
   for C in range(9):
      row = 218
      for L  in range(10):
         hood = original[row:row + hrow,col:col +hcol]
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
        # if L == 6:
        #    row = row-1
      mean = numpy.mean(letter)
      val = (letter[numpy.argmin(letter)])
      if mean - 8000 < val < mean + 8000:
         UID.append(chr(32))
      else:
         additional.append(numpy.argmin(letter))
     # additional[C] = numpy.argmax(letter)
      col = col + hcol + dcol
   print 'add', additional

   return lastName,firstName,UID,additional
Beispiel #28
0
def otsu_threshold(img, maxCount=255, verbose=False):
	"""
	:NAME:
		otsu_threshold

	:PURPOSE:
		this method generates a binary thresholded image based off of 
		Otsu's class discrimination method

	:CATEGORY:
		ipcv -- object recognition and thresholding tool

	:CALLING SEQUENCE:
		quantizedImage = quantize(img = inputImage,\
								 maxCount = max display level\
								 verbose = true or false)

	:INPUTS:
		img
			[numpy.ndarray]	input image to be quanitized
		maxCount
			[int] maximum pixel value in the output array
		verbose
			[boolean] whether or not to graph the histogram 

	:RETURN VALUE:
		tuple containing:
			returnTuple[0] -- binary numpy.array of the same shape as the input image
			returnTuple[1] -- threshold determined by otsu's method


	:ERROR CHECKING:
		TypeError
		ValueError
		RuntimeError

	:REQUIRES:
		np
		sys.exc_info
		os.path.split
		ipcv

	:MODIFICATION HISTORY:
		Engineer:	Jeff Maggio
		08/25/16:	otsu code

	"""
######################  BEGIN ERROR CHECKING  #######################
	if isinstance(img,np.ndarray) == True:
		dims = ipcv.dimensions(img,"dictionary")

		if dims["bands"] == 1:

			if len(img.shape) == 3:
				#making the array two dimensional if it only has 1 band 
				img = img.reshape(dims['rows'],dims['cols'])

		else:
			print("")
			print("input 'img' must be grayscale or single-banded")
			print("")
			raise RuntimeError

	else:
		print("")
		print("input 'img' must be a valid 2 dimensional numpy array, currently {0}".format(type(img)))
		print("")
		raise TypeError

	if isinstance(maxCount,int) == False:
		print("")
		print("input 'maxCount' must be an int, currently {0}".format(type(maxCount)))
		print("")
		raise TypeError
	elif maxCount <= 0:
		print("")
		print("input 'maxCount' must be greater than zero")
		print("")
		raise ValueError

	if isinstance(verbose,bool) == False:
		print("")
		print("input 'verbose' must be integer boolean , currently {0}".format(verbose))
		print("")
		raise TypeError


######################  END ERROR CHECKING  #######################

	try:

		numberCounts = maxCount + 1
		#generating the pdf and cdf
		hist,pdf,cdf = ipcv.histogram(img,histSize=numberCounts,ranges=[0,numberCounts])
		
		meanLevelArray = np.cumsum( np.arange(0,numberCounts) * pdf )
		muTotal = meanLevelArray[-1]

		sigmaSquaredBValues = np.zeros(numberCounts)
		startingK = np.where(cdf>0.0)[0][0]
		endingK = np.where(cdf<1.0)[0][-1]

		for k in range(startingK, endingK):
			muK = meanLevelArray[k]
			omegaK = cdf[k]
			sigmaSquaredB = ( ( (muTotal * omegaK) - muK )**2 ) / ( omegaK * (1-omegaK) )
			sigmaSquaredBValues[k] = sigmaSquaredB

		threshold = np.argmax(sigmaSquaredBValues)

		LUT = np.zeros( numberCounts )
		LUT[threshold+1:] = 1

		img = LUT[img]

		if verbose == True:
			values = (pdf,)
			colors = ('r',)
			filename = "image_pdf_wOtsu.eps"
			thresholdMarker = (threshold,)
			labels = ("pdf",)
			graph = ipcv.quickplot(values,colors,labels,filename=filename,verticalMarkers=thresholdMarker,\
				xLabel="Digital Counts",yLabel="probability",display=False)
			graph.annotate("otsu's Threshold", xy=(threshold, .01), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05))
			graph.show()

		return img.astype(np.uint8), threshold


	except Exception as e:
		print("===============================================================")
		exc_type, exc_obj, tb = exc_info()
		fname = split(tb.tb_frame.f_code.co_filename)[1]
		print("\r\nfile: {0}\r\n\r\nline: {1} \r\n\r\n{2}\r\n\r\n".format(fname,tb.tb_lineno,exc_obj,e))
		print("===============================================================")
Beispiel #29
0
    numberColumns = dimensions[1]
    if len(dimensions) == 3:
        numberBands = dimensions[2]
    else:
        numberBands = 1
        dataType = im.dtype

    return numberRows, numberColumns, numberBands, dataType


if __name__ == '__main__':

    import cv2
    import ipcv
    import os.path

    home = os.path.expanduser('~')
    path = os.path.join(home, 'src', 'python', 'examples', 'data')
    filename = os.path.join(path, 'lenna.tif')
    filename = os.path.join(path, 'redhat.ppm')
    filename = os.path.join(path, 'crowd.jpg')
    filename = os.path.join(path, 'checkerboard.tif')

    im = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
    print('Filename = {0}'.format(filename))
    print('Data type = {0}'.format(type(im)))
    print('Image shape = {0}'.format(im.shape))
    print('Image size = {0}'.format(im.size))

    print(ipcv.dimensions(im))
Beispiel #30
0
def read_info2(sheets, original):
   hood = numpy.ones((39,37))
   numRows, numCols, numBands, dtype = ipcv.dimensions(original)
  # original = ((original*1.0) - (sheets*1.0)) *255
   original = ((original*1.0) - (sheets*1.0)) *255
  # original = original.astype(numpy.unit8)
  # cv2.namedWindow('orig',cv2.WINDOW_AUTOSIZE)
  # cv2.imshow('orig', original)
  # cv2.waitKey()
   
   lastName = []
   drow = 11 
   dcol = 13
   hcol = 37
   hrow = 39
   col = 303 
   cv2.namedWindow('hood')
   letter = numpy.zeros((26,1))
   for C in range(11):
      row = 211
      for L  in range(26):
         hood = original[row:row + hrow,col:col +hcol]
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
         if L == 1 or L == 6 or L == 12 or L ==17 or L == 23:
            row = row-1
         print 'row',row
         cv2.imshow('hood',hood)
         cv2.waitKey(600)
      val = (letter[numpy.argmin(letter)])
      print 'lastval',val
      mean = numpy.mean(letter)
      print 'mean',mean
     # if mean - 3 < val < mean + 3:
     #    lastName.append(chr(32))
      if mean - 9000 < val < mean + 9000:
         lastName.append(chr(32))
         
      else:
         lastName.append(chr(numpy.argmin(letter)+65))
      col = col + hcol + dcol
   print 'lastname',lastName
  # print 'letter', letter
  # print 'row',row
  # print 'col',col
   
   firstName = [] 
   drow = 11
   dcol = 13
   hcol = 37
   hrow = 39
   col = 983
   cv2.namedWindow('hood')
   letter = numpy.zeros((26,1))
   for C in range(9):
      row = 211
      for L  in range(26):
         hood = original[row:row + hrow,col:col +hcol]
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
        # if L == 6:
         if L == 1 or L == 6 or L == 12 or L ==17 or L == 23:
            row = row-1
         print 'row',row
         cv2.imshow('hood',hood)
         cv2.waitKey(300)
      val = (letter[numpy.argmin(letter)])
      mean = numpy.mean(letter)
      if mean - 9000 < val < mean + 9000:
         firstName.append(chr(32))
         
      else:
         firstName.append(chr(numpy.argmin(letter)+65))
     # firstName[C] = numpy.argmax(letter)
      col = col + hcol + dcol
   print 'firstname',firstName
   
   '''
   '''
  # UID = numpy.zeros((9))
   UID = []
   drow = 11
   dcol = 13
   hcol = 37
   hrow = 39
   col = 1545 
   cv2.namedWindow('hood')
   letter = numpy.zeros((10,1))
   for C in range(9):
      row = 211
      for L  in range(10):
         hood = original[row:row + hrow,col:col +hcol]
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
        # if L == 6:
         if L == 1 or L == 6 or L == 12 or L ==17 or L == 23:
            row = row-1
         print 'row',row
         cv2.imshow('hood',hood)
         cv2.waitKey(300)
      mean = numpy.mean(letter)
      val = (letter[numpy.argmin(letter)])
      if mean - 9000 < val < mean + 9000:
         UID.append(chr(32))
      else:
         UID.append(numpy.argmin(letter))
     # UID[C] = numpy.argmax(letter)
      col = col + hcol + dcol
   
   print 'UID',UID
    
   #additional = numpy.zeros((9))
   additional = []
   drow = 11 
   dcol = 13
   hcol = 37
   hrow = 39
   col = 1545
   cv2.namedWindow('hood')
   letter = numpy.zeros((10,1))
   for C in range(9):
      row = 907
      for L  in range(10):
         hood = original[row:row + hrow,col:col +hcol]
         total = numpy.sum(hood)
         letter[L] = total
         row = row + drow +hrow
         if L == 3 or L == 8:
            row = row-1
         print 'row',row
         cv2.imshow('hood',hood)
         cv2.waitKey(300)
      mean = numpy.mean(letter)
      val = (letter[numpy.argmin(letter)])
      if mean - 8000 < val < mean + 8000:
         additional.append(chr(32))
      else:
         additional.append(numpy.argmin(letter))
     # additional[C] = numpy.argmax(letter)
      col = col + hcol + dcol
   print 'add', additional

   return lastName,firstName,UID,additional
Beispiel #31
0
def fftCorrelation(fiducial1C, blankSheetC):
   
   numRows, numCols, numBands, dataType = ipcv.dimensions(blankSheetC)
   numRows1, numCols1, numBands1, dataType1 = ipcv.dimensions(fiducial1C)
   print 'blank bands:', numBands
   print 'fiducial1 bands:', numBands1

   if numBands == 3:
      blankSheet = cv2.cvtColor(blankSheetC, cv.CV_BGR2GRAY)
   elif numBands == 1:
      blankSheet = blankSheetC

   if numBands1 == 3:
      fiducial1 = cv2.cvtColor(fiducial1C, cv.CV_BGR2GRAY)
   elif numBands2 == 1:
      fiducial1 = fiducial1C

   freqFid1 = numpy.fft.fft2(fiducial1)
   freqBlank = numpy.fft.fft2(blankSheet)

   magFid1 = numpy.absolute(freqFid1)
   magBlank = numpy.absolute(freqBlank)

   phaseFid1 = numpy.angle(freqFid1)
   phaseBlank = numpy.angle(freqBlank)

   correlation = magBlank * magFid1 * numpy.exp(1j * (phaseBlank - phaseFid1))
 
   corrSpat = numpy.fft.ifft2(correlation)
   corrSpat = numpy.absolute(numpy.fft.fftshift(corrSpat))

   print corrSpat
   dispCorrSpat = corrSpat / numpy.max(corrSpat)

   print dispCorrSpat.max(), dispCorrSpat.min()
   
   numberRows, numberColumns, numberBands, dataType1 = ipcv.dimensions(blankSheet)
   numIncorrect = numpy.zeros((numberRows, numberColumns))
   threshold = 0.9999999999999955
   #
   numIncorrect[dispCorrSpat < threshold] = 0
   #if response is greater than/equal to the threshold, a match occurs
   numIncorrect[dispCorrSpat >= threshold] = 1
   print numIncorrect
   totalIncorrect = numpy.sum(numIncorrect)
   print 'totalIncorrect', totalIncorrect    
   
   cv2.namedWindow('corrSpat', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('corrSpat', dispCorrSpat)
   cv2.waitKey() 

   locationMax = numpy.argmax(corrSpat)
   rowLoc, colLoc = numpy.unravel_index(locationMax, (numRows, numCols))
   displayIm = cv2.merge((blankSheet, blankSheet, blankSheet))
   print rowLoc, colLoc

   displayIm[rowLoc - 1:rowLoc+2, colLoc-1:colLoc+2, 2] = 0
   displayIm[rowLoc-1:rowLoc+2, colLoc-1:colLoc+2, 0:1] = 255

   cv2.namedWindow('displayIm', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('displayIm', displayIm)
   cv2.waitKey()
   cv2.imwrite('dotsInCir3.tif', displayIm)
   '''
   fftFid1 = numpy.fft.ifftshift(centerFreqFid1)
   fftBlank = numpy.fft.ifftshift(centerFreqBlank)
   Fid1 = numpy.fft.ifft2(fftFid1)
   Blank = numpy.fft.ifft2(fftBlank)
   '''
   return rowLoc, colLoc
def testRotation2():
   print 'hello'
   #sheets, img2 = ipcv.read_in_files('answer_sheets.pdf','original_scan_sheet.pdf')
   #colorimg1 = cv2.imread('test0001.tif', 0)          # queryImage
   #colorimg2 = cv2.imread('original.tif', 0)
   #print colorimg1
   colorimg1 = cv2.imread('girlRotated.jpeg')
   colorimg2 = cv2.imread('girl.jpeg')

   numRows, numCols, numBands, dataType = ipcv.dimensions(colorimg1)
   if numBands == 3:
      image1 = cv2.cvtColor(colorimg1, cv.CV_BGR2GRAY)
   elif numBands == 1:
      image1 = colorimg1

   numRows2, numCols2, numBands2, dataType2 = ipcv.dimensions(colorimg2)
   if numBands2 == 3:
      image2 = cv2.cvtColor(colorimg2, cv.CV_BGR2GRAY)
   elif numBands2 == 1:
      image2 = colorimg2
   #image1 = cv2.GaussianBlur(image1,(5,5),0)
   #image2 = cv2.GaussianBlur(image2,(5,5),0)
   mask = np.zeros((numRows, numCols)).astype(np.uint8)
   #3 circles
   #mask[690:773,19:105] = 1
   #mask[15:100,512:603] = 1
   #mask[700:780,490:590] = 1
   #First Name
   mask[25:43,230:347] = 1
   #3 Half Circles
   #mask[715:761,62:82] = 1
   #mask[712:776,548:568] = 1
   #mask[27:80,561:581] = 1
   #mask[375:385,146:206] = 1
   #Quarter Circle
   #mask[59:80,561:581] = 1
   #Additional Information
   mask[190:203,367:480] = 1
   #University ID
   mask[24:38,364:484] = 1
   #Last
   mask[25:35,70:92] = 1

   cv2.namedWindow('mask', cv2.WINDOW_NORMAL)
   cv2.imshow('mask', mask)
   cv2.waitKey()
   print 'mask dataType', mask.dtype
   print 'img1 datatype', image1.dtype
   print 'img2 datatype', image2.dtype
   #img2 = cv2.imread('scene.jpeg',0) # trainImage

   #initiate SIFT detector
   sift = cv2.SIFT()

   # find the keypoints and descriptors with SIFT
   keypoint1, descriptor1 = sift.detectAndCompute(image1,None)
   keypoint2, descriptor2 = sift.detectAndCompute(image2,None)
   print 'keypoint1', keypoint1
   # A combo of FAST and BRIEF
   #orb = cv2.ORB()
   #keypoint1, descriptor1 = orb.detectAndCompute(image1,None)
   #keypoint2, descriptor2 = orb.detectAndCompute(image2,None)

   i_params = dict(algorithm=0, trees=5)
   s_params = dict(checks=50)

   flann = cv2.FlannBasedMatcher(i_params, s_params)
   matches = flann.knnMatch(descriptor1, descriptor2, k=2)

   good_matches = []

   for m, n in matches:
      if m.distance < 0.7*n.distance:
         good_matches.append(m)

   src_points = np.float32([keypoint1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
   dst_points = np.float32([keypoint2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)

   print 'test', src_points
   print 'original', dst_points

   # create BFMatcher object
   #bfObject = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)

   # Match descriptors.
   #matches = bfObject.match(descriptor1,descriptor2)

   # Sort them in the order of their distance.
   good_matches = sorted(good_matches, key = lambda x:x.distance)

   # Draw first 10 matches.
   image3 = drawMatches(image1,keypoint1,image2,keypoint2,good_matches[:10])  
   #image3 = drawMatches(image1,src_points.astype(np.uint8),image2, dst_points(np.uint8),good_matches[:10])
   cv2.imwrite('matching.tif', image3)

   #Create Affine Transform
   M = cv2.getAffineTransform(src_points[0:3], dst_points[0:3])
   print M
   dst = cv2.warpAffine(image1, M, (numRows, numCols))
   print np.min(dst), np.max(dst)
   cv2.namedWindow('rotatedIm', cv2.WINDOW_AUTOSIZE)
   cv2.imshow('rotatedIm', dst.astype(np.uint8))
   cv2.waitKey()
Beispiel #33
0
def fft_display(img, videoFilename=None):
    try:
        img = img.copy()

        dims = ipcv.dimensions(img)
        r, c = dims["rows"], dims["cols"]
        temp = np.zeros((r, c))

        # generating FFT
        # FFT = np.fft.fftshift(np.fft.fft(img))
        # FFT = np.fft.fftshift( np.fft.fft2(img) )
        # logFFT = np.log( np.abs( FFT / np.sqrt(FFT.size) ) ).astype(ipcv.IPCV_8U)

        FFT = np.fft.fft2(img)
        # print("AVERAGE VALUE IS EQUAL TO:",FFT.flat[0])
        FFT = np.fft.fftshift(FFT)
        FFT = np.abs(FFT)
        logFFT = np.log10(FFT)
        logFFT = (logFFT / np.max(logFFT)) * 255

        print("MAX IS EQUAL TO:", np.max(logFFT))
        print("MIN IS EQUAL TO:", np.min(logFFT))

        # creating array to poulate with maximum values
        maximumValues = np.flipud(np.argsort(logFFT.flatten()))

        used = temp.copy()
        current = temp.copy()
        currentScaled = temp.copy()
        summed = temp.copy()

        #creating writer and image window
        cv2.namedWindow(videoFilename)
        writer = create_video_writer(img.shape, videoFilename)

        for freqIndex in maximumValues:
            # for index in np.arange(0,maximumValues.size,2)
            # puting frequency in 'used' array
            used.flat[freqIndex] = logFFT.flat[freqIndex]

            # returning the spatial sine wave for freq
            temp.flat[freqIndex] = logFFT.flat[freqIndex]
            current = np.fft.ifft2(temp)
            temp.flat[freqIndex] = 0

            print("MAX IS EQUAL TO:", np.max(current))
            print("MIN IS EQUAL TO:", np.min(current))

            #scaling the current
            currentScaled = (
                (current - np.min(current)) / np.max(current)) * 255

            #summing up all the freq
            summed = summed + current

            #stiching all images together
            frame = stich(img, logFFT, used, current, currentScaled, summed)

            print("frame dataType =", frame.dtype)
            #writing frame
            if writer.isOpened():
                writer.write(frame)

            #displaying image
            cv2.imshow(videoFilename, frame)

            action = ipcv.flush()
            if action == "pause":
                action = ipcv.flush()
                if action == "pause":
                    continue

            elif action == "exit":
                writer.release()
                sys.exit()

    except Exception as e:
        ipcv.debug(e)