content: # /usr/bin/python
  # To run this test you need python nose tools installed
  # Run test just use:
  #   nosetest tests.py
  #
  # *Note: If you add additional test, please prefix the function name
  # to the type of operation being performed.  For instance modifying an
  # image, test_image_erode().  If you are looking for lines, then
  # test_detection_lines().  This makes it easier to verify visually
  # that all the correct test per operation exist
  
  import os, sys, pickle, operator
  from SimpleCV import *
  from nose.tools import with_setup, nottest
  
  VISUAL_TEST = False  # if TRUE we save the images - otherwise we DIFF against them - the default is False
  SHOW_WARNING_TESTS = False  # show that warnings are working - tests will pass but warnings are generated.
  
  #colors
  black = Color.BLACK
  white = Color.WHITE
  red = Color.RED
  green = Color.GREEN
  blue = Color.BLUE
  
  ###############
  # TODO -
  # Examples of how to do profiling
  # Examples of how to do a single test -
  # UPDATE THE VISUAL TESTS WITH EXAMPLES.
  # Fix exif data
  # Turn off test warnings using decorators.
  # Write a use the tests doc.
  
  #images
  barcode = "../sampleimages/barcode.png"
  testimage = "../sampleimages/9dots4lines.png"
  testimage2 = "../sampleimages/aerospace.jpg"
  whiteimage = "../sampleimages/white.png"
  blackimage = "../sampleimages/black.png"
  testimageclr = "../sampleimages/statue_liberty.jpg"
  testbarcode = "../sampleimages/barcode.png"
  testoutput = "../sampleimages/9d4l.jpg"
  tmpimg = "../sampleimages/tmpimg.jpg"
  greyscaleimage = "../sampleimages/greyscale.jpg"
  logo = "../sampleimages/simplecv.png"
  logo_inverted = "../sampleimages/simplecv_inverted.png"
  ocrimage = "../sampleimages/ocr-test.png"
  circles = "../sampleimages/circles.png"
  webp = "../sampleimages/simplecv.webp"
  
  #alpha masking images
  topImg = "../sampleimages/RatTop.png"
  bottomImg = "../sampleimages/RatBottom.png"
  maskImg = "../sampleimages/RatMask.png"
  alphaMaskImg = "../sampleimages/RatAlphaMask.png"
  alphaSrcImg = "../sampleimages/GreenMaskSource.png"
  
  #standards path
  standard_path = "./standard/"
  
  
  #Given a set of images, a path, and a tolerance do the image diff.
  def imgDiffs(test_imgs,name_stem,tolerance,path):
      count = len(test_imgs)
      for idx in range(0,count):
          lhs = test_imgs[idx].applyLayers() # this catches drawing methods
          fname = standard_path+name_stem+str(idx)+".jpg"
          rhs = Image(fname)
          if( lhs.width == rhs.width and lhs.height == rhs.height ):
              diff = (lhs-rhs)
              val = np.average(diff.getNumpy())
              if( val > tolerance ):
                  print val
                  return True
      return False
  
  #Save a list of images to a standard path.
  def imgSaves(test_imgs, name_stem, path=standard_path):
      count = len(test_imgs)
      for idx in range(0,count):
          fname = standard_path+name_stem+str(idx)+".jpg"
          test_imgs[idx].save(fname)#,quality=95)
  
  #perform the actual image save and image diffs.
  def perform_diff(result,name_stem,tolerance=3.0,path=standard_path):
      if(VISUAL_TEST): # save the correct images for a visual test
          imgSaves(result,name_stem,path)
      else: # otherwise we test our output against the visual test
          if( imgDiffs(result,name_stem,tolerance,path) ):
              assert False
          else:
              pass
  
  def test_image_stretch():
      img = Image(greyscaleimage)
      stretched = img.stretch(100,200)
      if(stretched == None):
          assert False
  
      result = [stretched]
      name_stem = "test_stretch"
      perform_diff(result,name_stem)
  
  
  #These function names are required by nose test, please leave them as is
  def setup_context():
      img = Image(testimage)
  
  def destroy_context():
      img = ""
  
  @with_setup(setup_context, destroy_context)
  def test_image_loadsave():
      img = Image(testimage)
      img.save(testoutput)
      if (os.path.isfile(testoutput)):
          os.remove(testoutput)
          pass
      else:
          assert False
  
  def test_image_numpy_constructor():
      img = Image(testimage)
      grayimg = img.grayscale()
  
      chan3_array = np.array(img.getMatrix())
      chan1_array = np.array(img.getGrayscaleMatrix())
  
      img2 = Image(chan3_array)
      grayimg2 = Image(chan1_array)
  
      if (img2[0,0] == img[0,0] and grayimg2[0,0] == grayimg[0,0]):
          pass
      else:
          assert False
  
  def test_image_bitmap():
      img1 = Image("lenna")
      img2 = Image("lenna")
      img2 = img2.smooth()
      result = [img1,img2]
      name_stem = "test_image_bitmap"
      perform_diff(result,name_stem)
  
  # # Image Class Test
  
  def test_image_scale():
      img = Image(testimage)
      thumb = img.scale(30,30)
      if(thumb == None):
          assert False
      result = [thumb]
      name_stem = "test_image_scale"
      perform_diff(result,name_stem)
  
  def test_image_copy():
      img = Image(testimage2)
      copy = img.copy()
  
      if (img[1,1] != copy[1,1] or img.size() != copy.size()):
          assert False
  
      result = [copy]
      name_stem = "test_image_copy"
      perform_diff(result,name_stem)
  
      pass
  
  
  def test_image_getitem():
      img = Image(testimage)
      colors = img[1,1]
      if (colors[0] == 255 and colors[1] == 255 and colors[2] == 255):
          pass
      else:
          assert False
  
  def test_image_getslice():
      img = Image(testimage)
      section = img[1:10,1:10]
      if(section == None):
          assert False
  
  
  def test_image_setitem():
      img = Image(testimage)
      img[1,1] = (0, 0, 0)
      newimg = Image(img.getBitmap())
      colors = newimg[1,1]
      if (colors[0] == 0 and colors[1] == 0 and colors[2] == 0):
          pass
      else:
          assert False
  
      result = [newimg]
      name_stem = "test_image_setitem"
      perform_diff(result,name_stem)
  
  
  def test_image_setslice():
      img = Image(testimage)
      img[1:10,1:10] = (0,0,0) #make a black box
      newimg = Image(img.getBitmap())
      section = newimg[1:10,1:10]
      for i in range(5):
          colors = section[i,0]
          if (colors[0] != 0 or colors[1] != 0 or colors[2] != 0):
              assert False
      pass
      result = [newimg]
      name_stem = "test_image_setslice"
      perform_diff(result,name_stem)
  
  
  def test_detection_findCorners():
      img = Image(testimage2)
      corners = img.findCorners(25)
      corners.draw()
      if (len(corners) == 0):
          assert False
      result = [img]
      name_stem = "test_detection_findCorners"
      perform_diff(result,name_stem)
  
  
  def test_color_meancolor():
      a = np.arange(0, 256)
      b = a[::-1]
      c = np.copy(a)/2
      a = a.reshape(16, 16)
      b = b.reshape(16, 16)
      c = c.reshape(16, 16)
      imgarr = np.dstack((a, b, c))
      img = Image(imgarr)
  
      b, g, r = img.meanColor('BGR')
      if not (127 < r < 128 and 127 < g < 128 and 63 < b < 64):
          assert False
  
      r, g, b = img.meanColor('RGB')
      if not (127 < r < 128 and 127 < g < 128 and 63 < b < 64):
          assert False
  
      h, s, v = img.meanColor('HSV')
      if not (83 < h < 84 and 191 < s < 192 and 191 < v < 192):
          assert False
  
      x, y, z = img.meanColor('XYZ')
      if not (109 < x < 110 and 122 < y < 123 and 77 < z < 79):
          assert False
  
      gray = img.meanColor('Gray')
      if not (120 < gray < 121):
          assert False
  
      y, cr, cb = img.meanColor('YCrCb')
      if not (120 < y < 121 and 133 < cr < 134 and 96 < cb < 97):
          assert False
  
      h, l, s = img.meanColor('HLS')
      if not (84 < h < 85 and 117 < l < 118 and 160 < s < 161):
          assert False
      pass
  
  def test_image_smooth():
      img = Image(testimage2)
      result = []
      result.append(img.smooth())
      result.append(img.smooth('bilateral', (3,3), 4, 1))
      result.append(img.smooth('blur', (3, 3)))
      result.append(img.smooth('median', (3, 3)))
      result.append(img.smooth('gaussian', (5,5), 0))
      result.append(img.smooth('bilateral', (3,3), 4, 1,grayscale=False))
      result.append(img.smooth('blur', (3, 3),grayscale=True))
      result.append(img.smooth('median', (3, 3),grayscale=True))
      result.append(img.smooth('gaussian', (5,5), 0,grayscale=True))
      name_stem = "test_image_smooth"
      perform_diff(result,name_stem)
      pass
  
  def test_image_gammaCorrect():
      img = Image(topImg)
      img2 = img.gammaCorrect(1)
      img3 = img.gammaCorrect(0.5)
      img4 = img.gammaCorrect(2)
      result = []
      result.append(img3)
      result.append(img4)
      name_stem = "test_image_gammaCorrect"
      perform_diff(result, name_stem)
      if ((img3.meanColor() >= img2.meanColor()) and (img4.meanColor() <= img2.meanColor())):
          pass
      else:
          assert False
  
  def test_image_binarize():
      img =  Image(testimage2)
      binary = img.binarize()
      binary2 = img.binarize((60, 100, 200))
      hist = binary.histogram(20)
      hist2 = binary2.histogram(20)
  
      result = [binary,binary2]
      name_stem = "test_image_binarize"
      perform_diff(result,name_stem)
  
      if (hist[0] + hist[-1] == np.sum(hist) and hist2[0] + hist2[-1] == np.sum(hist2)):
          pass
      else:
          assert False
  
  def test_image_binarize_adaptive():
      img =  Image(testimage2)
      binary = img.binarize(-1)
      hist = binary.histogram(20)
  
      result = [binary]
      name_stem = "test_image_binarize_adaptive"
      perform_diff(result,name_stem)
  
      if (hist[0] + hist[-1] == np.sum(hist)):
          pass
      else:
          assert False
  
  def test_image_invert():
      img = Image(testimage2)
      clr = img[1,1]
      img = img.invert()
  
      result = [img]
      name_stem = "test_image_invert"
      perform_diff(result,name_stem)
  
      if (clr[0] == (255 - img[1,1][0])):
          pass
      else:
          assert False
  
  
  def test_image_size():
      img = Image(testimage2)
      (width, height) = img.size()
      if type(width) == int and type(height) == int and width > 0 and height > 0:
          pass
      else:
          assert False
  
  def test_image_drawing():
      img = Image(testimageclr)
      img.drawCircle((img.width/2, img.height/2), 10,thickness=3)
      img.drawCircle((img.width/2, img.height/2), 15,thickness=5,color=Color.RED)
      img.drawCircle((img.width/2, img.height/2), 20)
      img.drawLine((5, 5), (5, 8))
      img.drawLine((5, 5), (10, 10),thickness=3)
      img.drawLine((0, 0), (img.width, img.height),thickness=3,color=Color.BLUE)
      img.drawRectangle(20,20,10,5)
      img.drawRectangle(22,22,10,5,alpha=128)
      img.drawRectangle(24,24,10,15,width=-1,alpha=128)
      img.drawRectangle(28,28,10,15,width=3,alpha=128)
      result = [img]
      name_stem = "test_image_drawing"
      perform_diff(result,name_stem)
  
  def test_image_draw():
      img = Image("lenna")
      newimg = Image("simplecv")
      lines = img.findLines()
      newimg.draw(lines)
      lines.draw()
      result = [newimg, img]
      name_stem = "test_image_draw"
      perform_diff(result, name_stem, 5)
  
  
  def test_image_splitchannels():
      img = Image(testimageclr)
      (r, g, b) = img.splitChannels(True)
      (red, green, blue) = img.splitChannels()
      result = [r,g,b,red,green,blue]
      name_stem = "test_image_splitchannels"
      perform_diff(result,name_stem)
      pass
  
  def test_image_histogram():
      img = Image(testimage2)
      h = img.histogram(25)
  
      for i in h:
          if type(i) != int:
              assert False
  
      pass
  
  def test_detection_lines():
      img = Image(testimage2)
      lines = img.findLines()
      lines.draw()
      result = [img]
      name_stem = "test_detection_lines"
      perform_diff(result,name_stem)
  
      if(lines == 0 or lines == None):
          assert False
  
  def test_detection_lines_standard():
      img = Image(testimage2)
      lines = img.findLines(useStandard=True)
      lines.draw()
      result = [img]
      name_stem = "test_detection_lines_standard"
      perform_diff(result,name_stem)
  
      if(lines == 0 or lines == None):
          assert False
  
  def test_detection_feature_measures():
      img = Image(testimage2)
  
      fs = FeatureSet()
      fs.append(Corner(img, 5, 5))
      fs.append(Line(img, ((2, 2), (3,3))))
      bm = BlobMaker()
      result = bm.extract(img)
      fs.extend(result)
  
      for f in fs:
          a = f.area()
          l = f.length()
          c = f.meanColor()
          d = f.colorDistance()
          th = f.angle()
          pts = f.coordinates()
          dist = f.distanceFrom() #distance from center of image
  
      fs2 = fs.sortAngle()
      fs3 = fs.sortLength()
      fs4 = fs.sortColorDistance()
      fs5 = fs.sortArea()
      fs1 = fs.sortDistance()
      pass
  
  def test_detection_blobs_appx():
      img = Image("lenna")
      blobs = img.findBlobs()
      blobs[-1].draw(color=Color.RED)
      blobs[-1].drawAppx(color=Color.BLUE)
      result = [img]
  
      img2 = Image("lenna")
      blobs = img2.findBlobs(appx_level=11)
      blobs[-1].draw(color=Color.RED)
      blobs[-1].drawAppx(color=Color.BLUE)
      result.append(img2)
  
      name_stem = "test_detection_blobs_appx"
      perform_diff(result,name_stem,5.00)
      if blobs == None:
          assert False
  
  def test_detection_blobs():
      img = Image(testbarcode)
      blobs = img.findBlobs()
      blobs.draw(color=Color.RED)
      result = [img]
      #TODO - WE NEED BETTER COVERAGE HERE
      name_stem = "test_detection_blobs"
      perform_diff(result,name_stem,5.00)
  
      if blobs == None:
          assert False
  
  def test_detection_blobs_lazy():
  
      img = Image("lenna")
      b = img.findBlobs()
      result = []
  
      s = pickle.dumps(b[-1]) # use two otherwise it w
      b2 =  pickle.loads(s)
  
      result.append(b[-1].mImg)
      result.append(b[-1].mMask)
      result.append(b[-1].mHullImg)
      result.append(b[-1].mHullMask)
  
      result.append(b2.mImg)
      result.append(b2.mMask)
      result.append(b2.mHullImg)
      result.append(b2.mHullMask)
  
      #TODO - WE NEED BETTER COVERAGE HERE
      name_stem = "test_detection_blobs_lazy"
      perform_diff(result,name_stem,6.00)
  
  
  def test_detection_blobs_adaptive():
      img = Image(testimage)
      blobs = img.findBlobs(-1, threshblocksize=99)
      blobs.draw(color=Color.RED)
      result = [img]
      name_stem = "test_detection_blobs_adaptive"
      perform_diff(result,name_stem,5.00)
  
      if blobs == None:
          assert False
  
  def test_detection_blobs_smallimages():
      # Check if segfault occurs or not
      img = Image("../sampleimages/blobsegfaultimage.png")
      blobs = img.findBlobs()
      # if no segfault, pass
  
  def test_detection_blobs_convexity_defects():
      img = Image('lenna')
      blobs = img.findBlobs()
      b = blobs[-1]
      feat = b.getConvexityDefects()
      points = b.getConvexityDefects(returnPoints=True)
      if len(feat) <= 0 or len(points) <= 0:
          assert False
      pass
  
  def test_detection_barcode():
      try:
          import zbar
      except:
          return None
  
      img1 = Image(testimage)
      img2 = Image(testbarcode)
  
      if( SHOW_WARNING_TESTS ):
          nocode = img1.findBarcode()
          if nocode: #we should find no barcode in our test image
              assert False
          code = img2.findBarcode()
          code.draw()
          if code.points:
              pass
          result = [img1,img2]
          name_stem = "test_detection_barcode"
          perform_diff(result,name_stem)
  
  
      else:
          pass
  
  def test_detection_x():
      tmpX = Image(testimage).findLines().x()[0]
  
      if (tmpX > 0 and Image(testimage).size()[0]):
          pass
      else:
          assert False
  
  def test_detection_y():
      tmpY = Image(testimage).findLines().y()[0]
  
      if (tmpY > 0 and Image(testimage).size()[0]):
          pass
      else:
          assert False
  
  def test_detection_area():
      img = Image(testimage2)
      bm = BlobMaker()
      result = bm.extract(img)
      area_val = result[0].area()
  
      if(area_val > 0):
          pass
      else:
          assert False
  
  def test_detection_angle():
      angle_val = Image(testimage).findLines().angle()[0]
  
  def test_image():
      img = Image(testimage)
      if(isinstance(img, Image)):
          pass
      else:
          assert False
  
  def test_color_colordistance():
      img = Image(blackimage)
      (r,g,b) = img.splitChannels()
      avg = img.meanColor()
  
      c1 = Corner(img, 1, 1)
      c2 = Corner(img, 1, 2)
      if (c1.colorDistance(c2.meanColor()) != 0):
          assert False
  
      if (c1.colorDistance((0,0,0)) != 0):
          assert False
  
      if (c1.colorDistance((0,0,255)) != 255):
          assert False
  
      if (c1.colorDistance((255,255,255)) != sqrt(255**2 * 3)):
          assert False
  
      pass
  
  def test_detection_length():
      img = Image(testimage)
      val = img.findLines().length()
  
      if (val == None):
          assert False
      if (not isinstance(val, np.ndarray)):
          assert False
      if (len(val) < 0):
          assert False
  
      pass
  
  def test_detection_sortangle():
      img = Image(testimage)
      val = img.findLines().sortAngle()
  
      if(val[0].x < val[1].x):
          pass
      else:
          assert False
  
  def test_detection_sortarea():
      img = Image(testimage)
      bm = BlobMaker()
      result = bm.extract(img)
      val = result.sortArea()
      #FIXME: Find blobs may appear to be broken. Returning type none
  
  def test_detection_sortLength():
      img = Image(testimage)
      val = img.findLines().sortLength()
      #FIXME: Length is being returned as euclidean type, believe we need a universal type, either Int or scvINT or something.
  
  #def test_distanceFrom():
  #def test_sortColorDistance():
  #def test_sortDistance():
  
  def test_image_add():
      imgA = Image(blackimage)
      imgB = Image(whiteimage)
  
      imgC = imgA + imgB
  
  def test_color_curve_HSL():
      y = np.array([[0,0],[64,128],[192,128],[255,255]])  #These are the weights
      curve = ColorCurve(y)
      img = Image(testimage)
      img2 = img.applyHLSCurve(curve,curve,curve)
      img3 = img-img2
  
      result = [img2,img3]
      name_stem = "test_color_curve_HLS"
      perform_diff(result,name_stem)
  
      c = img3.meanColor()
      if( c[0] > 2.0 or c[1] > 2.0 or c[2] > 2.0 ): #there may be a bit of roundoff error
          assert False
  
  def test_color_curve_RGB():
      y = np.array([[0,0],[64,128],[192,128],[255,255]])  #These are the weights
      curve = ColorCurve(y)
      img = Image(testimage)
      img2 = img.applyRGBCurve(curve,curve,curve)
      img3 = img-img2
  
      result = [img2,img3]
      name_stem = "test_color_curve_RGB"
      perform_diff(result,name_stem)
  
      c = img3.meanColor()
      if( c[0] > 1.0 or c[1] > 1.0 or c[2] > 1.0 ): #there may be a bit of roundoff error
          assert False
  
  def test_color_curve_GRAY():
      y = np.array([[0,0],[64,128],[192,128],[255,255]])  #These are the weights
      curve = ColorCurve(y)
      img = Image(testimage)
      gray = img.grayscale()
      img2 = img.applyIntensityCurve(curve)
  
      result = [img2]
      name_stem = "test_color_curve_GRAY"
      perform_diff(result,name_stem)
  
      g=gray.meanColor()
      i2=img2.meanColor()
      if( g[0]-i2[0] > 1 ): #there may be a bit of roundoff error
          assert False
  
  def test_image_dilate():
      img=Image(barcode)
      img2 = img.dilate(20)
  
      result = [img2]
      name_stem = "test_image_dilate"
      perform_diff(result,name_stem)
      c=img2.meanColor()
  
      if( c[0] < 254 or c[1] < 254 or c[2] < 254 ):
          assert False;
  
  def test_image_erode():
      img=Image(barcode)
      img2 = img.erode(100)
  
      result = [img2]
      name_stem = "test_image_erode"
      perform_diff(result,name_stem)
  
      c=img2.meanColor()
      print(c)
      if( c[0] > 0 or c[1] > 0 or c[2] > 0 ):
          assert False;
  
  def test_image_morph_open():
      img = Image(barcode);
      erode= img.erode()
      dilate = erode.dilate()
      result = img.morphOpen()
      test = result-dilate
      c=test.meanColor()
      results = [result]
      name_stem = "test_image_morph_open"
      perform_diff(results,name_stem)
  
      if( c[0] > 1 or c[1] > 1 or c[2] > 1 ):
          assert False;
  
  def test_image_morph_close():
      img = Image(barcode)
      dilate = img.dilate()
      erode = dilate.erode()
      result = img.morphClose()
      test = result-erode
      c=test.meanColor()
  
      results = [result]
      name_stem = "test_image_morph_close"
      perform_diff(results,name_stem)
  
  
      if( c[0] > 1 or c[1] > 1 or c[2] > 1 ):
          assert False;
  
  def test_image_morph_grad():
      img = Image(barcode)
      dilate = img.dilate()
      erode = img.erode()
      dif = dilate-erode
      result = img.morphGradient()
      test = result-dif
      c=test.meanColor()
  
      results = [result]
      name_stem = "test_image_morph_grad"
      perform_diff(results,name_stem)
  
  
      if( c[0] > 1 or c[1] > 1 or c[2] > 1 ):
          assert False
  
  def test_image_rotate_fixed():
      img = Image(testimage2)
      img2=img.rotate(180, scale = 1)
      img3=img.flipVertical()
      img4=img3.flipHorizontal()
      img5 = img.rotate(70)
      img6 = img.rotate(70,scale=0.5)
  
      results = [img2,img3,img4,img5,img6]
      name_stem = "test_image_rotate_fixed"
      perform_diff(results,name_stem)
  
      test = img4-img2
      c=test.meanColor()
      print(c)
      if( c[0] > 5 or c[1] > 5 or c[2] > 5 ):
          assert False
  
  
  def test_image_rotate_full():
      img = Image(testimage2)
      img2=img.rotate(180,"full",scale = 1)
  
      results = [img2]
      name_stem = "test_image_rotate_full"
      perform_diff(results,name_stem)
  
      c1=img.meanColor()
      c2=img2.meanColor()
      if( abs(c1[0]-c2[0]) > 5 or abs(c1[1]-c2[1]) > 5 or abs(c1[2]-c2[2]) > 5 ):
          assert False
  
  def test_image_shear_warp():
      img = Image(testimage2)
      dst =  ((img.width/2,0),(img.width-1,img.height/2),(img.width/2,img.height-1))
      s = img.shear(dst)
  
  
      color = s[0,0]
      if (color != (0,0,0)):
          assert False
  
      dst = ((img.width*0.05,img.height*0.03),(img.width*0.9,img.height*0.1),(img.width*0.8,img.height*0.7),(img.width*0.2,img.height*0.9))
      w = img.warp(dst)
  
      results = [s,w]
      name_stem = "test_image_shear_warp"
      perform_diff(results,name_stem)
  
      color = s[0,0]
      if (color != (0,0,0)):
          assert False
  
      pass
  
  def test_image_affine():
      img = Image(testimage2)
      src =  ((0,0),(img.width-1,0),(img.width-1,img.height-1))
      dst =  ((img.width/2,0),(img.width-1,img.height/2),(img.width/2,img.height-1))
      aWarp = cv.CreateMat(2,3,cv.CV_32FC1)
      cv.GetAffineTransform(src,dst,aWarp)
      atrans = img.transformAffine(aWarp)
  
      aWarp2 = np.array(aWarp)
      atrans2 = img.transformAffine(aWarp2)
  
      test = atrans-atrans2
      c=test.meanColor()
  
      results = [atrans,atrans2]
  
      name_stem = "test_image_affine"
      perform_diff(results,name_stem)
  
      if( c[0] > 1 or c[1] > 1 or c[2] > 1 ):
          assert False
  
  def test_image_perspective():
      img = Image(testimage2)
      src = ((0,0),(img.width-1,0),(img.width-1,img.height-1),(0,img.height-1))
      dst = ((img.width*0.05,img.height*0.03),(img.width*0.9,img.height*0.1),(img.width*0.8,img.height*0.7),(img.width*0.2,img.height*0.9))
      pWarp = cv.CreateMat(3,3,cv.CV_32FC1)
      cv.GetPerspectiveTransform(src,dst,pWarp)
      ptrans = img.transformPerspective(pWarp)
      pWarp2 = np.array(pWarp)
      ptrans2 = img.transformPerspective(pWarp2)
      test = ptrans-ptrans2
      np_test = test.getNumpy()
      mc=test.meanColor()
      results = [ptrans,ptrans2]
      name_stem = "test_image_perspective"
      # Threshold kept high, otherwise test will fail
      # difference between original image warped image will be always huge
      perform_diff(results,name_stem, 100)
  
      if( mc[0] > 100 or mc[1] > 100 or mc[2] > 100 ):
          assert False
  
  def test_image_horz_scanline():
      img = Image(logo)
      sl = img.getHorzScanline(10)
      if( sl.shape[0]!=img.width or sl.shape[1]!=3 ):
          assert False
  
  def test_image_vert_scanline():
      img = Image(logo)
      sl = img.getVertScanline(10)
      if( sl.shape[0]!=img.height or sl.shape[1]!=3 ):
          assert False
  
  def test_image_horz_scanline_gray():
      img = Image(logo)
      sl = img.getHorzScanlineGray(10)
      if( sl.shape[0]!=img.width or sl.shape[1]!=1 ):
          assert False
  
  def test_image_vert_scanline_gray():
      img = Image(logo)
      sl = img.getVertScanlineGray(10)
      if( sl.shape[0]!=img.height or sl.shape[1]!=1 ):
          assert False
  
  def test_image_get_pixel():
      img = Image(logo)
      px = img.getPixel(0,0)
      print(px)
      if(px[0] != 0 or px[1] != 0 or px[2] != 0 ):
          assert False
  
  def test_image_get_gray_pixel():
      img = Image(logo)
      px = img.getGrayPixel(0,0)
      if(px != 0):
          assert False
  
  
  def test_camera_calibration():
      fakeCamera = FrameSource()
      path = "../sampleimages/CalibImage"
      ext = ".png"
      imgs = []
      for i in range(0,10):
          fname = path+str(i)+ext
          img = Image(fname)
          imgs.append(img)
  
      fakeCamera.calibrate(imgs)
      #we're just going to check that the function doesn't puke
      mat = fakeCamera.getCameraMatrix()
      if( type(mat) != cv.cvmat ):
          assert False
      #we're also going to test load in save in the same pass
      matname = "TestCalibration"
      if( False == fakeCamera.saveCalibration(matname)):
          assert False
      if( False == fakeCamera.loadCalibration(matname)):
          assert False
  
  def test_camera_undistort():
      fakeCamera = FrameSource()
      fakeCamera.loadCalibration("./StereoVision/Default")
      img = Image("../sampleimages/CalibImage0.png")
      img2 = fakeCamera.undistort(img)
  
      results = [img2]
      name_stem = "test_camera_undistort"
      perform_diff(results,name_stem,tolerance=12)
  
      if (not img2): #right now just wait for this to return
          assert False
  
  def test_image_crop():
      img = Image(logo)
      x = 5
      y = 6
      w = 10
      h = 20
      crop = img.crop(x,y,w,h)
      crop2 = img[x:(x+w),y:(y+h)]
      crop6 = img.crop(0,0,10,10)
      # if( SHOW_WARNING_TESTS ):
      #     crop7 = img.crop(0,0,-10,10)
      #     crop8 = img.crop(-50,-50,10,10)
      #     crop3 = img.crop(-3,-3,10,20)
      #     crop4 = img.crop(-10,10,20,20,centered=True)
      #     crop5 = img.crop(-10,-10,20,20)
  
      tests = []
      tests.append(img.crop((50,50),(10,10))) # 0
      tests.append(img.crop([10,10,40,40])) # 1
      tests.append(img.crop((10,10,40,40))) # 2
      tests.append(img.crop([50,50],[10,10])) # 3
      tests.append(img.crop([10,10],[50,50])) # 4
  
      roi = np.array([10,10,40,40])
      pts1 = np.array([[50,50],[10,10]])
      pts2 = np.array([[10,10],[50,50]])
      pt1 = np.array([10,10])
      pt2 = np.array([50,50])
  
      tests.append(img.crop(roi)) # 5
      tests.append(img.crop(pts1)) # 6
      tests.append(img.crop(pts2)) # 7
      tests.append(img.crop(pt1,pt2)) # 8
      tests.append(img.crop(pt2,pt1)) # 9
  
      xs = [10,10,10,20,20,20,30,30,40,40,40,50,50,50]
      ys = [10,20,50,20,30,40,30,10,40,50,10,50,10,42]
      lots = zip(xs,ys)
  
      tests.append(img.crop(xs,ys)) # 10
      tests.append(img.crop(lots)) # 11
      tests.append(img.crop(np.array(xs),np.array(ys))) # 12
      tests.append(img.crop(np.array(lots))) # 14
  
      i = 0
      failed = False
      for img in tests:
          if( img is None or img.width != 40 and img.height != 40 ):
              print "FAILED CROP TEST " + str(i) + " " + str(img)
              failed = True
          i = i + 1
  
      if(failed):
          assert False
      results = [crop,crop2,crop6]
      name_stem = "test_image_crop"
      perform_diff(results,name_stem)
  
      diff = crop-crop2;
      c=diff.meanColor()
      if( c[0] > 0 or c[1] > 0 or c[2] > 0 ):
          assert False
  
  def test_image_region_select():
      img = Image(logo)
      x1 = 0
      y1 = 0
      x2 = img.width
      y2 = img.height
      crop = img.regionSelect(x1,y1,x2,y2)
  
      results = [crop]
      name_stem = "test_image_region_select"
      perform_diff(results,name_stem)
  
      diff = crop-img;
      c=diff.meanColor()
      if( c[0] > 0 or c[1] > 0 or c[2] > 0 ):
          assert False
  
  def test_image_subtract():
      imgA = Image(logo)
      imgB = Image(logo_inverted)
      imgC = imgA - imgB
      results = [imgC]
      name_stem = "test_image_subtract"
      perform_diff(results,name_stem)
  
  def test_image_negative():
      imgA = Image(logo)
      imgB = -imgA
      results = [imgB]
      name_stem = "test_image_negative"
      perform_diff(results,name_stem)
  
  
  def test_image_divide():
      imgA = Image(logo)
      imgB = Image(logo_inverted)
  
      imgC = imgA / imgB
  
      results = [imgC]
      name_stem = "test_image_divide"
      perform_diff(results,name_stem)
  
  def test_image_and():
      imgA = Image(barcode)
      imgB = imgA.invert()
  
  
      imgC = imgA & imgB # should be all black
  
      results = [imgC]
      name_stem = "test_image_and"
      perform_diff(results,name_stem)
  
  
  def test_image_or():
      imgA = Image(barcode)
      imgB = imgA.invert()
  
      imgC = imgA | imgB #should be all white
  
      results = [imgC]
      name_stem = "test_image_or"
      perform_diff(results,name_stem)
  
  
  def test_image_edgemap():
      imgA = Image(logo)
      imgB = imgA._getEdgeMap()
      #results = [imgB]
      #name_stem = "test_image_edgemap"
      #perform_diff(results,name_stem)
  
  
  def test_color_colormap_build():
      cm = ColorModel()
      #cm.add(Image(logo))
      cm.add((127,127,127))
      if(cm.contains((127,127,127))):
          cm.remove((127,127,127))
      else:
          assert False
  
      cm.remove((0,0,0))
      cm.remove((255,255,255))
      cm.add((0,0,0))
      cm.add([(0,0,0),(255,255,255)])
      cm.add([(255,0,0),(0,255,0)])
      img = cm.threshold(Image(testimage))
      c=img.meanColor()
  
      #if( c[0] > 1 or c[1] > 1 or c[2] > 1 ):
      #  assert False
  
      cm.save("temp.txt")
      cm2 = ColorModel()
      cm2.load("temp.txt")
      img = Image("logo")
      img2 = cm2.threshold(img)
      cm2.add((0,0,255))
      img3 = cm2.threshold(img)
      cm2.add((255,255,0))
      cm2.add((0,255,255))
      cm2.add((255,0,255))
      img4 = cm2.threshold(img)
      cm2.add(img)
      img5 = cm2.threshold(img)
  
      results = [img,img2,img3,img4,img5]
      name_stem = "test_color_colormap_build"
      perform_diff(results,name_stem)
  
      #c=img.meanColor()
      #if( c[0] > 1 or c[1] > 1 or c[2] > 1 ):
      #  assert False
  
  
  def test_feature_height():
      imgA = Image(logo)
      lines = imgA.findLines(1)
      heights = lines.height()
  
      if(len(heights) <= 0 ):
          assert False
      else:
          pass
  
  def test_feature_width():
      imgA = Image(logo)
      lines = imgA.findLines(1)
      widths = lines.width()
  
      if(len(widths) <= 0):
          assert False
      else:
          pass
  
  def test_feature_crop():
      imgA = Image(logo)
  
      lines = imgA.findLines()
  
      croppedImages = lines.crop()
  
      if(len(croppedImages) <= 0):
          assert False
      else:
          pass
  
  
  def test_color_conversion_func_BGR():
      #we'll just go through the space to make sure nothing blows up
      img = Image(testimage)
      results = []
      results.append(img.toBGR())
      results.append(img.toRGB())
      results.append(img.toHLS())
      results.append(img.toHSV())
      results.append(img.toXYZ())
  
      bgr = img.toBGR()
  
      results.append(bgr.toBGR())
      results.append(bgr.toRGB())
      results.append(bgr.toHLS())
      results.append(bgr.toHSV())
      results.append(bgr.toXYZ())
  
      name_stem = "test_color_conversion_func_BGR"
      perform_diff(results,name_stem,tolerance=4.0)
  
  
  def test_color_conversion_func_RGB():
      img = Image(testimage)
      if( not img.isBGR() ):
          assert False
      rgb = img.toRGB()
  
      foo = rgb.toBGR()
      if( not foo.isBGR() ):
          assert False
  
      foo = rgb.toRGB()
      if( not foo.isRGB() ):
          assert False
  
      foo = rgb.toHLS()
      if( not foo.isHLS() ):
          assert False
  
      foo = rgb.toHSV()
      if( not foo.isHSV() ):
          assert False
  
      foo = rgb.toXYZ()
      if( not foo.isXYZ() ):
          assert False
  
  def test_color_conversion_func_HSV():
      img = Image(testimage)
      hsv = img.toHSV()
      results = [hsv]
      results.append(hsv.toBGR())
      results.append(hsv.toRGB())
      results.append(hsv.toHLS())
      results.append(hsv.toHSV())
      results.append(hsv.toXYZ())
      name_stem = "test_color_conversion_func_HSV"
      perform_diff(results,name_stem,tolerance=4.0 )
  
  
  def test_color_conversion_func_HLS():
      img = Image(testimage)
  
      hls = img.toHLS()
      results = [hls]
  
      results.append(hls.toBGR())
      results.append(hls.toRGB())
      results.append(hls.toHLS())
      results.append(hls.toHSV())
      results.append(hls.toXYZ())
  
      name_stem = "test_color_conversion_func_HLS"
      perform_diff(results,name_stem,tolerance=4.0)
  
  
  def test_color_conversion_func_XYZ():
      img = Image(testimage)
  
      xyz = img.toXYZ()
      results = [xyz]
      results.append(xyz.toBGR())
      results.append(xyz.toRGB())
      results.append(xyz.toHLS())
      results.append(xyz.toHSV())
      results.append(xyz.toXYZ())
  
      name_stem = "test_color_conversion_func_XYZ"
      perform_diff(results,name_stem,tolerance=8.0)
  
  
  def test_blob_maker():
      img = Image("../sampleimages/blockhead.png")
      blobber = BlobMaker()
      results = blobber.extract(img)
      print(len(results))
      if( len(results) != 7 ):
          assert False
  
  def test_blob_holes():
      img = Image("../sampleimages/blockhead.png")
      blobber = BlobMaker()
      blobs = blobber.extract(img)
      count = 0
      blobs.draw()
      results = [img]
      name_stem = "test_blob_holes"
      perform_diff(results,name_stem,tolerance=3.0)
  
  
      for b in blobs:
          if( b.mHoleContour is not None ):
              count = count + len(b.mHoleContour)
      if( count != 7 ):
  