def feature_match_bf_img(img1, img2):
	"""
	Brute-force feature matching between two images.
	Returns matches, keypoints of image 1, 
		    keypoints of image 2, descriptors of 1, 
		    descriptors of 2
	"""
	gray1 = ImageIO.grayscale(img1)
	gray2 = ImageIO.grayscale(img2)
	cv2.ocl.setUseOpenCL(False)
	orb = cv2.ORB()
	kp1, des1 = orb.detectAndCompute(gray1, None)
	kp2, des2 = orb.detectAndCompute(gray2, None)
	matches = feature_match_bf(kp1, des1, kp2, des2)[0]
	return matches, kp1, kp2, des1, des2
def findPoints(poinsts):
    for dog_octaves in poinsts:
        nextgen_list = []
        for sacle in range(2):
            a = dog_octaves[sacle]
            b = dog_octaves[sacle + 1]
            c = dog_octaves[sacle + 2]
            result = b
            height, width = b.shape[:2]
            # print(width, height)
            for jj in range(height):
                for kk in range(width):
                    target = b[jj][kk]
                    window = []
                    for i in range(3):
                        for j in range(3):
                            try:
                                window.append(a[jj - 1 + i][kk - 1 + j])
                            except:
                                print('')
                    for i in range(3):
                        for j in range(3):
                            try:
                                if i != 1 and j != 1:
                                    window.append(b[jj - 1 + i][kk - 1 + j])
                            except:
                                print('')
                    for i in range(3):
                        for j in range(3):
                            try:
                                window.append(c[jj - 1 + i][kk - 1 + j])
                            except:
                                print('')
                    tmax = max(window)
                    tmin = min(window)
                    if target > tmax:
                        result[jj][kk] = target
                        # result[jj][kk] = 255
                    elif target < tmin:
                        result[jj][kk] = target
                        # result[jj][kk] = 255
                    else:
                        result[jj][kk] = 0
            print('how keypoints')
            io.showImage(result)
            nextgen_list.append(result)
        keypoints_octaves.append(nextgen_list)
    return keypoints_octaves
Example #3
0
def test_mass():

    dataPath = 'C:/Tomosynthesis/localtest/'
    fileName = '5131R-recon08_45-1.tif'
    outputPath = 'C:/Tomosynthesis/localtest/res/'

    im = ImageIO.imReader(dataPath,fileName, 'tif',2)
    
    # padding borarders
    '''
    paddingrd = 10
    bordares = ((paddingrd,paddingrd),(paddingrd,paddingrd))
    paddingv = 10000
    bordarevs = ((paddingv,paddingv),(paddingv,paddingv))
    im = np.lib.pad(im.data[0], bordares, 'constant',constant_values = bordarevs)
    '''
    
    eqimg = histEqualization.histEqualization(im.data[0], 16)
    denoised = AT_denoising.DenoisingAW(eqimg)
    denoised = AT_denoising.DenoisingAW(denoised)
    denoised = AT_denoising.DenoisingAW(denoised)
    img = AT_denoising.DenoisingAW(denoised)
    tiffLib.imsave(outputPath + 'denoised.tif',img)

    # g(I)
    gI = morphsnakes.gborders(img, alpha=1, sigma=8)
    tiffLib.imsave(outputPath + 'gI.tif',np.float32(gI))
    # Morphological GAC. Initialization of the level-set.
    mgac = morphsnakes.MorphGAC(gI, smoothing=2, threshold=0.035, balloon=-1)
    mgac.levelset = circle_levelset(img.shape, (img.shape[0]/2, img.shape[1]/2), 140, scalerow=0.75)
    
    # Visual evolution.
    ppl.figure()
    ls = morphsnakes.evolve_visual(mgac, num_iters=110, background=img)
    tiffLib.imsave(outputPath + 'ls.tif',np.float32(ls))
Example #4
0
def test_func():
    """Please specify the image tiff stack directory, file name and output
    path. Extracted masses list will be save in a workspace file for further use.
    Also please specify how many cores will be allocated for the parallel process.
    """


    dataPath = '/home/yanbin/Tomosynthesis/data/tiffs_3d/5016/'
    outputPath = '/home/yanbin/Tomosynthesis/script_test/'
    fileName = '5016EMML08.tif'

    ## load image data
    im = ImageIO.imReader(dataPath,fileName, 'tif')

    ## allocate cpu source
    pool = Pool(processes=6)
    params =[(i,im.data[i]) for i in range(im.size_2)]

    ## run in parallel
    sliceList = []    
    sliceList = pool.map(mass3d.parallelWrapper,params)
    
    ## save the workspace
    output = open(outputPath + 'suspicious.pkl', 'wb')
    pickle.dump(sliceList, output)
    output.close()
Example #5
0
def creatTrainigSam_3D(dataPath, iRnum = 6,iSnum = 12, gRnum = 4,gSnum = 12):
    """ Creat training samples(3D) and compute features for each training sample 

    Parameters
    ----------
    dataPath: str
        The directory where training image ROIs are stores.
    opt: str
        Options for compute features.
    iRnum: integer
        The number of rings to be divided in computing intensity features
    iSnum: integer
        The number of sectors to be divided in computing intensity features
    gRnum: integer
        The number of rings to be divided in computing gradient features
    gSnum: integer
        The number of sectors to be divided in computing gradient features
    """

    file_list = os.listdir(dataPath)

    LightPatchList = []
    bagid = 0
    instanceid = 0
    for fil in file_list:
        im = ImageIO.imReader(dataPath, fil,'tif',3)

        for i in range(im.size_2):

            # Calculating intensity features
            patch = TPatch.TPatch()
            patch.initialize(im.data[i])
            int_feats = patch.getIntenfeats(iRnum,iSnum)

            # Calculating segment features         
            seg_feats = patch.getSegmentFeats()

            # Calculating gradient features
            im.downSample(rate = 2)
            eqimg = histEqualization.histEqualization(im.sampled_data[i], 16)
            smoothimg = filters.gaussian_filter(eqimg, sigma = 2, order=0, output=None, mode='reflect', cval=0.0, truncate=4.0)
            patch = TPatch.TPatch()
            patch.initialize(smoothimg)
            gr_feats = patch.getGradfeats(gRnum,gSnum)
            
            feats = np.hstack((int_feats, gr_feats, seg_feats))

            lightPatch = TPatch.TLightPatch()
            lightPatch.pdata = im.data[i]
            lightPatch.feats = feats
            lightPatch.patch_center = (im.data[i].shape[0]/2, im.data[i].shape[1]/2)
            lightPatch.bagID = bagid
            lightPatch.instanceID = instanceid
            LightPatchList.append(lightPatch)

            instanceid = instanceid + 1
        
        bagid = bagid + 1

    return LightPatchList
Example #6
0
def LK_Optical_Flow(image, p0, mask=None):
    lk_params = dict(winSize=(50, 50),
                     maxLevel=5,
                     criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
                               10, 0.03))
    image_old = image
    image_old = cv2.add(image_old,
                        np.zeros(np.shape(image_old), dtype=np.uint8),
                        mask=mask)
    linemask = np.zeros_like(image)
    while 1:
        #image=cv2.add(image,np.zeros(np.shape(image),dtype=np.uint8),mask=mask)
        p1, st, err = cv2.calcOpticalFlowPyrLK(image_old, image, p0, None,
                                               **lk_params)
        try:
            good_new = p1[st == 1]
            good_old = p0[st == 1]
        except TypeError:
            warn("Lose track")
            return
        for i, (new, old) in enumerate(zip(good_new, good_old)):
            a, b = new.ravel()
            c, d = old.ravel()
            linemask = cv2.line(linemask, (a, b), (c, d), color[i].tolist(), 2)
            image = cv2.circle(image, (a, b), 5, color[i].tolist(), -1)
        img = cv2.add(image, linemask)
        k = cv2.waitKey(30) & 0xff
        if k == 27:
            break
        image_old = image.copy()
        p0 = good_new.reshape(-1, 1, 2)
        image = (yield img)
Example #7
0
def otsu(img):
	"""
	Method to threshold via a OTSU binarization
	"""
	gray = ImageIO.grayscale(img)
	gray = cv2.GaussianBlur(img, (5,5), 0)
	ret, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
	return th
Example #8
0
def fft_img(img):
	"""
	Fast Fourier Transform in 2-D.
	"""
	gray = ImageIO.grayscale(img)
	f = np.fft.fft2(gray)
	fshift = np.fft.fftshift(f)
	return fshift
def good_corners(img, numFeatures = 25):
	"""
	Finds corners via Shi-Tomasi Good Features To Track.
	Returns corners.
	"""
	gray = ImageIO.grayscale(img)
	corners = cv2.goodFeautresToTrack(gray, numFeatures, 0.01, 10)
	corners = np.int0(corners)
	return corners
 def setUp(self):  
     imageFile = '../test/test.jpg'
     self.image = ImageIO.cv2read(imageFile)
     self.grayscale = cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY)
     self.stats = stats()
     self.fft = fft()
     self.feats = Features()
     self.lap = Laplacian()
     self.edges = Edges()
Example #11
0
def adaptiveMean(img):
	"""
	Method to threshold using a threshold value that is 
	the mean of neighbourhood area.
	"""
	gray = ImageIO.grayscale(img)
	gray = cv2.medianBlur(img, 5)
	meanThresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
	return meanThresh	
def harris_corner_detector(img, blockSize = 2, ksize = 3, k = 0.04):
	"""
	Harris Corner Detection.
	"""
	gray = ImageIO.grayscale(img)
	gray = np.float32(gray)
	dst = cv2.cornerHarris(gray, blockSize, ksize, k)
	dst = cv2.dilate(dst, None)
	return dst
   def test_cvread(self):
       img = ImageIO.cvread(self.imageFile)
       tmpImg = cv.LoadImage(self.imageFile)
       cv.AbsDiff(img,tmpImg,img)
 
       mat = cv.GetMat(img)
       arr = numpy.asarray(mat)
       
       equalityBool = (arr.all() == 0)
       self.assertTrue(equalityBool)
Example #14
0
def adaptiveGaussian(img):
	"""
	Method to threshold using a threshold value that is 
	the weighted sum of neighbourhood values where 
	weights are a gaussian window.
	"""
	gray = ImageIO.grayscale(img)
	gray = cv2.medianBlur(img, 5)
	gaussThresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
	return gaussThresh
Example #15
0
def threshold(img, threshold = 127, invert=False):
	"""
	Method to quickly compute the binary image.
	"""
	gray = ImageIO.grayscale(img)
	if invert:
		ret, thresh = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV)
		return thresh
	ret, thresh = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
	return thresh
Example #16
0
def getOctaves(img):

    octaves = []
    b = 0.5
    # print(b)
    for x in range(4):
        List = []
        a = b
        # print(a)
        for y in range(5):
            a = a * math.sqrt(2)
            List.append(cv2.GaussianBlur(img, (5, 5), a))
            # print(a)
            io.showImage(List[y])
        b *= 2
        octaves.append(List)
        height, width = img.shape[:2]
        img = cv2.resize(img, (int(width / 2), int(height / 2)),
                         interpolation=cv2.INTER_AREA)
    return octaves
def removeLowThreshold(low_threshold, points):
    low_threshold_keypoints = []
    for list in points:
        scales_list = []
        for index, a in enumerate(list):
            print(index)
            result = a
            height, width = a.shape[:2]
            # avoid low_threshold pixels
            for j in range(height):
                for k in range(width):
                    if a[j][k] < low_threshold[index]:
                        result[j][k] = 0
                    else:
                        result[j][k] = 255
            low_threshold[index] *= 0.75
            io.showImage(result)
            scales_list.append(result)
        low_threshold_keypoints.append(scales_list)
    return low_threshold_keypoints
def removeEdge(points, scale_space):
    mask_x = [[1, 0, -1], [2, 0, -2], [1, 0, -1]]
    mask_y = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]]
    for a, list in enumerate(points):
        scale_list = []
        imX = cv.filter2D(scale_space[a][0], -1, kernel=np.array(mask_x))
        imY = cv.filter2D(scale_space[a][0], -1, kernel=np.array(mask_y))
        for index, item in enumerate(list):
            height, width = item.shape[:2]

            for j in range(height):
                for k in range(width):
                    if imX[j][k] != 0 and imY[j][k] != 0:
                        if 0.5 < imX[j][k] / imY[j][k] < 1.5 and item[j][
                                k] != 0:
                            item[j][k] = 0
                    else:
                        item[j][k] = 0
            io.showImage(item)
            scale_list.append(item)
        keypoints.append(scale_list)
    return keypoints
def my_svm():
    trainSet_x, trainSet_y, testSet_x, testSet_y = ImageIO.loadSVMImage()

    # clf = svm.SVC(C=100.0, kernel='rbf', gamma=0.03)
    clf = svm.LinearSVC()

    print('start fit')
    clf.fit(trainSet_x, trainSet_y)
    print('finish fit')

    predictions = [int(a) for a in clf.predict(testSet_x)]
    predictions_2 = [int(a) for a in clf.predict(trainSet_x)]
    num_correct = sum(int(a == y) for a, y in zip(predictions, testSet_y))
    num_correct_2 = sum(int(a == y) for a, y in zip(predictions_2, trainSet_y))

    print("%s of %s test values correct." % (num_correct, len(testSet_y)))
    print("%s of %s train values correct." % (num_correct_2, len(trainSet_y)))
Example #20
0
def worddetect():
	print "start run..."
	filename = "train_data/image_label.csv"

	dataModelSet = DataModelSet(ImageIO.read_image_label_model_file(filename))
	print "num_examples : %d" %(dataModelSet.num_examples)

	#dataModelpart = dataModelSet.next_batch(5)
	#for dataModel in dataModelpart:
	#	dataModel.discription()

	epochs = 10000

	# 输入变量,x为图像,y为标签
	x = tf.placeholder(dtype=tf.float32, shape=[None, 224, 224,3], name='x')
	y = tf.placeholder(dtype=tf.float32, shape=[None, 224, 224,1], name='y')
	hedmodel = HedNetModel("vgg16.npy")
	score = hedmodel.build(x,is_training = True)
	print "score.shape : "
	print score.shape
	cost = class_balanced_sigmoid_cross_entropy(score,y)
	accucy = 1 - cost;

	# 建立会话
	with tf.Session() as sess:
	# 初始化变量
		sess.run(tf.global_variables_initializer())
		for i in range(epochs):
			print "training... "
			# 批量数据,大小为5
			tmpDataList = []
			tmpLabelList = []
			dataModelpart = dataModelSet.next_batch(5)
			for tmpDataModel in dataModelpart:
				tmpDataList.append(tmpDataModel.imageData)
				tmpLabelList.append(tmpDataModel.labelData)
			x_batch = np.array(tmpDataList)
			y_batch = np.array(tmpLabelList)

			c = sess.run(cost, feed_dict={x:x_batch, y:y_batch})
			print "cost:"
			print c

	print "stop run..."	
Example #21
0
def getHeaderBitmap():
	''' Get the header bitmap if specified, or use a default.  '''
	if Utils.getMainWin():
		if Model.race and Model.race.headerImage:
			try:
				bitmap = ImageIO.toBitmapFromBuf( Model.race.headerImage )
				return bitmap
			except:
				pass
		graphicFName = Utils.getMainWin().getGraphicFName()
		extension = os.path.splitext( graphicFName )[1].lower()
		bitmapType = {
			'.gif': wx.BITMAP_TYPE_GIF,
			'.png': wx.BITMAP_TYPE_PNG,
			'.jpg': wx.BITMAP_TYPE_JPEG,
			'.jpeg':wx.BITMAP_TYPE_JPEG }.get( extension, wx.BITMAP_TYPE_PNG )
		bitmap = wx.Bitmap( graphicFName, bitmapType )
	else:
		bitmap = wx.Bitmap( os.path.join(Utils.getImageFolder(), 'CrossMgrHeader.png'), wx.BITMAP_TYPE_PNG )
	return bitmap
Example #22
0
def getHeaderBitmap():
	''' Get the header bitmap if specified, or use a default.  '''
	if Utils.getMainWin():
		if Model.race and Model.race.headerImage:
			try:
				bitmap = ImageIO.toBitmapFromBuf( Model.race.headerImage )
				return bitmap
			except:
				pass
		graphicFName = Utils.getMainWin().getGraphicFName()
		extension = os.path.splitext( graphicFName )[1].lower()
		bitmapType = {
			'.gif': wx.BITMAP_TYPE_GIF,
			'.png': wx.BITMAP_TYPE_PNG,
			'.jpg': wx.BITMAP_TYPE_JPEG,
			'.jpeg':wx.BITMAP_TYPE_JPEG }.get( extension, wx.BITMAP_TYPE_PNG )
		bitmap = wx.Bitmap( graphicFName, bitmapType )
	else:
		bitmap = wx.Bitmap( os.path.join(Utils.getImageFolder(), 'CrossMgrHeader.png'), wx.BITMAP_TYPE_PNG )
	return bitmap
Example #23
0
def test_func():
    """You can conver a single smv file to 3D tiff by specifying
    data_path, output_path, fileName and set the SigleConvert flag to 1.

    You can conver a batch of smv files to 3D tiffs by specifying
    root data_path, output_path and set the BatchConvert flag to 1.

    """

    ## Please specify paths ##
    data_path = '/home/yanbin/Tomosynthesis/data/SAP_test_datasets/Screening_30_cases/6002/'
    output_path = '/home/yanbin/Tomosynthesis/script_test/'
    fileName = '6002L06.smv'

    ## Please specify Parameters ##
    BatchConvert = 0
    SigleConvert = 0
    dim = 3

    ## data_path check
    if not os.path.isdir(data_path):
	print "Data directory:\n"+ data_path +"\ndoes not exist"
	sys.exit()

    ## Format convert batch
    if BatchConvert == 1:
        print 'here'
        dir_list = os.listdir(data_path)
        print dir_list
        for dirc in dir_list:
            print dirc
            if os.path.isdir(data_path + dirc):
                # make directory for output files
                opath = output_path + dirc + '/'
                print opath
                if not os.path.isdir(opath):
                    os.makedirs(opath)
                    
                file_list = os.listdir(data_path + dirc)    
                for fil in file_list: 
                    im = ImageIO.imReader(data_path + dirc + '/', fil, 'smv')
                    ImageIO.imWriter(opath, fil.strip('smv') + 'tif',im,dim)

    ## Format convert single
    if SigleConvert == 1:
        im = ImageIO.imReader(data_path,fileName, 'smv')
        ImageIO.imWriter(output_path, fileName.strip('smv') + 'tif',im, dim)
def imageHandler(imgfile):
    retStrings = []
    
    if imgfile in seen:
        return
    
    if os.path.isdir(os.path.join(args.directory, imgfile)):
        temp = os.listdir(os.path.join(args.directory, imgfile))
        for f in temp:
            images.append(os.path.join(imgfile, f))
        return
    
    # silently skip the bin files that have the gps data
    if imgfile.endswith('bin'):
        return
    # alert to other files that were skipped
    if not (imgfile.endswith('png') | imgfile.endswith('jpg')):
        sys.stderr.write("Skipped file: " + imgfile + "\n")
        return
    
    if args.verbose:
        sys.stderr.write("Parsing " + imgfile + "\n")
    
    retStrings.append( imgfile + "\t" )
    
    img = ImageIO.cv2read(os.path.join(args.directory, imgfile))
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ngray = Normalization.equalizeHistograms(gray)
    ngray = cv2.GaussianBlur(ngray, (3,3), 0)
    
    feats.detect_kp_ORB(ngray)
    retStrings.append( str(feats.numberKeyPoints()) + "\t" + str(feats.medianKeyPointSize()) + "\t" + str(feats.meanKeyPointSize()) )
    
    for i in range(15):
        retStrings.append("\t" + str(feats.numKeyPoints(i*10)))
    retStrings.append("\n")
    
    return retStrings
Example #25
0
def test_func():
    """Please specify the data directory and file name.This function runs
    the detection for a 3D stack.
    """

    dataPath = 'C:/Tomosynthesis/localtest/'
    outputPath = 'C:/Tomosynthesis/test_script/'   
    fileName = '5092-1.tif'

    # Loading data
    im = ImageIO.imReader(dataPath,fileName, 'tif',3)

    # run detection in parallel
    mc_Lists = []   
    pool = Pool(processes=1)
    params =[(i,im.data[i]) for i in range(im.size_2)]
    mc_Lists = pool.map(mc.parallelWrapper,params)
    
    global_id = mc.MC_connect_3d(mc_Lists)
    gloabal_list = mc.MCs_constuct_3d(mc_Lists,global_id)
    MC_List_3D = mc.MCs_constrain(gloabal_list)

    for item in MC_List_3D:
        print(item.center, item.intensity, item.volume)
Example #26
0
            out.append("使用中")
    return out


def GetCapturePointList(image, n):  #image为所要交互获取点的图像,n为想要获取的点的个数
    im_array = np.array(image)
    pylab.imshow(im_array)
    X = pylab.ginput(n)  # x 为列表,元素为坐标 例:[(x1,y1),(x2,y2),......]
    pylab.close()
    return X


if __name__ == "__main__":
    import imutils

    reader = image.reader("E:/[工程项目]/[数据集]/[图书馆占座识别视频样本]/00129_1.mp4")
    _, a = reader.read()
    _, b = reader.read(False)

    print("=" * 10, "蒙版", "=" * 10)
    #    mask=Mask_Square(reader.size,100,100,50)
    pointlist = np.array([[242, 351], [407, 353], [398, 478], [213, 479]],
                         dtype=np.int32)
    pointlist = pointlist.reshape([1, 4, 2])
    mask = Mask_Polygon(a.shape, pointlist)
    #cv2.imshow("mask",mask)
    #cv2.imshow("s",a)
    addresult = cv2.add(a, np.zeros(np.shape(a), dtype=np.uint8), mask=mask)
    #cv2.imshow("add",addresult)

    print("=" * 10, "特征点提取", "=" * 10)
Example #27
0
def main():

    ## Please specify paths ##
    data_path = '/home/yanbin/Tomosynthesis/data/SAP_test_datasets/Screening_30_cases/'
    output_path = '/home/yanbin/Tomosynthesis/data/tiffs_3d/'
    exe_path= '/home/yanbin/Tomosynthesis/code/'

    ## Please specify Run Flags ##
    FormatConvert = 1		
    AWDenoising = 0
    ContrastEnhancement = 0

    ## Please specify parameters ##
    dim = 3               # For format convert: save as 2d slices / 3d stack
    opt = 'asymptotic'    # For AWdenoising inverse transform options
    block_m=5
    block_n=5   # For AWdenoising Wiener filter window size block_m = block_n

    ###################### Avalability Check #######################

    # data_path check
    if not os.path.isdir(data_path):
	print "Data directory:\n"+ data_path +"\ndoes not exist"
	sys.exit()
	
    # exe_path check
    if not os.path.isdir(exe_path):
	print "Executable directory:\n"+ exe_path +"\ndoes not exist"
	sys.exit()
  
    ###################### Format Convert #######################
    
    if FormatConvert == 1:
        dir_list = os.listdir(data_path)
        print dir_list
        for dirc in dir_list:
            print dirc
            if os.path.isdir(data_path + dirc):
                # make directory for output files
                opath = output_path + dirc + '/'
                print opath
                if not os.path.isdir(opath):
                    os.makedirs(opath)
                    
                file_list = os.listdir(data_path + dirc)    
                for fil in file_list: 
                    im = ImageIO.imReader(data_path + dirc + '/', fil, 'smv')
                    ImageIO.imWriter(opath, fil.strip('smv') + 'tif',im,dim)

    ############################# Denoising ##########################
    if AWDenoising == 1:
        dir_list = os.listdir(data_path)
        print dir_list
        for dirc in dir_list:
            print dirc
            if os.path.isdir(data_path + dirc):
                # make directory for output files
                opath = output_path + dirc + '/'
                print opath
                if not os.path.isdir(opath):
                    os.makedirs(opath)
                    
                file_list = os.listdir(data_path + dirc)    
                for fil in file_list: 
                    im = ImageIO.imReader(data_path + dirc + '/', fil, 'tif',2)
                    denoised = AT_denoising.DenoisingAW(im.data[0], opt = 'asymptotic', block_m=5,block_n=5)
                    tiffLib.imsave(opath + 'denoised_' + fil,denoised)


    ###################### Contrast enhancement #######################
    if ContrastEnhancement == 1:
        dir_list = os.listdir(data_path)
        print dir_list
        for dirc in dir_list:
            print dirc
            if os.path.isdir(data_path + dirc):
                # make directory for output files
                opath = output_path + dirc + '/'
                print opath
                if not os.path.isdir(opath):
                    os.makedirs(opath)
                    
                file_list = os.listdir(data_path + dirc)    
                for fil in file_list: 
                    im = ImageIO.imReader(data_path + dirc + '/', fil, 'tif',2)
                    enhanced = histEqualization.histEqualization(im.data[0], 16)
                    tiffLib.imsave(opath + 'enhanced_' + fil,enhanced)
Example #28
0
        data_projected = Dimreduction.dim_Reduction(data, label, opt, n_components=2, visualize = True)
        classifier = classification.classifier(data_projected,label)
        classifier.train(opt ='SVM')
        classifier.classify()
    '''

    ############################# Mass 3D extraction ########################################
      
    dataPath = '/home/yanbin/Tomosynthesis/data/tiffs_3d/5016/'
    paraPath = '/home/yanbin/localtest/'
    outputPath = '/home/yanbin/Tomosynthesis/results/5016/'
    im_name = '5016EMML08.tif'
    

    # loading 
    im = ImageIO.imReader(dataPath,im_name, 'tif',3)
    print (im.size_0,im.size_1,im.size_2)
    
    control_name = 'feats_control_1.txt'
    cancer_name = 'feats_cancer.txt'
    control = np.loadtxt(paraPath + control_name)
    cancer = np.loadtxt(paraPath + cancer_name)

    # training
    data = np.vstack((control,cancer))
    label = np.zeros((control.shape[0] + cancer.shape[0],),np.int)
    label[0:control.shape[0]] = 1
    
    data_projected = Dimreduction.dim_Reduction(data, label, opt='randtree', n_components=5, visualize = False)
    classifier = classification.classifier(data_projected,label)
    classifier.train(opt ='SVM')
Example #29
0
import ImageIO as io
from SiftSteps import LoG, \
    ScaleSpace as scale_space, \
    findingKeyPoint as key_point, \
    gettingRideOfLowContrastKeypoints as decrese_keypoints, \
    GenerateFeature as gn, \
    KeypointOrientations as key_orientation

img = io.getImage("test2.jpg")

octaves = scale_space.getOctaves(img)

log_approximations = LoG.getDoGOctaves(octaves)

points = key_point.findPoints(octaves)

points = decrese_keypoints.removeKeypoints([2, 4], points, octaves)

oriented_points = key_orientation.orientations(points, octaves)

final_points = gn.generate_feature(oriented_points, points, octaves)
Example #30
0
import ImageIO
import TImage
import tiffLib

from scipy import ndimage as nd
import scipy
from skimage.filter import gabor_kernel
import numpy as np
import time
from numpy.fft import fft, ifft, fft2, ifft2, fftshift

dataPath = 'C:/Tomosynthesis/localtest/'
fileName = 'test-crop.tif'
outputPath = 'C:/Tomosynthesis/localtest/res/'
im = ImageIO.imReader(dataPath,fileName, 'tif',2)


kernel = np.real(gabor_kernel(0.0185, 0, 20, 20/float(0.9)))
print kernel.shape

start = time.clock()
temp_response = nd.convolve(im.data[0], kernel, mode='nearest')
elapsed = (time.clock() - start)
print elapsed

start = time.clock()
data = np.lib.pad(im.data[0], ((0,kernel.shape[0]),(0,kernel.shape[1])),'edge')
temp_response_2 = np.fft.irfft2(np.fft.rfft2(data) * np.fft.rfft2(kernel,data.shape))
temp_response_2 = temp_response_2[kernel.shape[0]/2:data.shape[0] - kernel.shape[0]/2,kernel.shape[1]/2:data.shape[1] - kernel.shape[1]/2]
elapsed = (time.clock() - start)
print elapsed
Example #31
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'objects_list',
        help='List of objects (.json)'
    )
    args = parser.parse_args()

    reader = open(os.path.join(os.environ['FS_ROOT'], args.objects_list), 'rt')
    data = json.load(reader)
    reader.close()
    input_file = data['input_file']
    output_dir = os.path.join(os.environ['FS_ROOT'], 'dataset', os.path.splitext(os.path.basename(input_file))[0])
    offset = min([data['frames'][f]['frame_id'] for f in range(len(data['frames']))])
    clip = (f + offset) / 900
    if args.objects_list.find('selected') == -1:
        sub_dir = 'clip{0:03d}'.format(clip)
    else:
        sub_dir = 'selected'
    if os.path.isfile('{0}/{1}/All/objects.json'.format(output_dir, sub_dir)) and os.path.isfile('{0}/{1}/Export/objects.json'.format(output_dir, sub_dir)):
        return
    elif os.path.isfile('{0}/{1}/All/objects.json'.format(output_dir, sub_dir)):
        reader = open('{0}/{1}/All/objects.json'.format(output_dir, sub_dir), 'rt')
        data = json.load(reader)
        reader.close()
    else:
        if not os.path.exists('{0}/{1}/All'.format(output_dir, sub_dir)):
            os.makedirs('{0}/{1}/All'.format(output_dir, sub_dir))
        if not os.path.exists('{0}/{1}/Export'.format(output_dir, sub_dir)):
            os.makedirs('{0}/{1}/Export'.format(output_dir, sub_dir))

    if os.path.isfile(os.path.join(os.environ['FS_ROOT'], input_file)):
        cap = cv2.VideoCapture(os.path.join(os.environ['FS_ROOT'], input_file))
        if cap.isOpened() == False:
            print('Cannot open input file: ' + os.path.join(os.environ['FS_ROOT'], input_file))
            exit(1)
        cap.set(cv2.CAP_PROP_POS_FRAMES,offset)
    else:
        filelist = sorted(glob.glob(os.path.join(os.environ['FS_ROOT'], input_file, '*.jpg')))
    
    for f in range(len(data['frames'])):
        if os.path.isfile(os.path.join(os.environ['FS_ROOT'], input_file)):
            ret,img = cap.read()
        else:
            img = cv2.imread(filelist[f + offset])
            ret = img is not None

        if ret:
            for r in range(len(data['frames'][f]['frame_rois'])):
                #print json.dumps(data['frames'][f]['frame_rois'][r], indent = 4)
                roi = (data['frames'][f]['frame_rois'][r]['roi_x'], data['frames'][f]['frame_rois'][r]['roi_y'], data['frames'][f]['frame_rois'][r]['roi_w'], data['frames'][f]['frame_rois'][r]['roi_h'])
                print roi
                if not os.path.isfile('{0}/{1}/All/objects.json'.format(output_dir, sub_dir)):
                    output = '{0}/{1}/Import/{2}/images/frame{3:06d}/{3:06d}_{4:06d}.jpg'.format(output_dir, sub_dir, data['frames'][f]['frame_rois'][r]['roi_label']['label_name'], data['frames'][f]['frame_id'], data['frames'][f]['frame_rois'][r]['roi_id'])
                    print output
                    ImageIO.saveImg(output, img, roi)
                    output = '{0}/{1}/All/images/frame{2:06d}/{2:06d}_{3:06d}.jpg'.format(output_dir, sub_dir, data['frames'][f]['frame_id'], data['frames'][f]['frame_rois'][r]['roi_id'])
                    ImageIO.saveImg(output, img, roi)
                if not os.path.isfile('{0}/{1}/Export/objects.json'.format(output_dir, sub_dir)) and data['frames'][f]['frame_rois'][r]['roi_label']['label_name'] != 'Unsorted':
                    output = '{0}/{1}/Export/{2}/{3:06d}_{4:06d}.jpg'.format(output_dir, sub_dir, data['frames'][f]['frame_rois'][r]['roi_label']['label_name'], data['frames'][f]['frame_id'], data['frames'][f]['frame_rois'][r]['roi_id'])
                    print output
                    ImageIO.saveImg(output, img, roi)
    if not os.path.isfile('{0}/{1}/All/objects.json'.format(output_dir, sub_dir)):
        shutil.copy(os.path.join(os.environ['FS_ROOT'], args.objects_list), '{0}/{1}/All/objects.json'.format(output_dir, sub_dir))
    if not os.path.isfile('{0}/{1}/Export/objects.json'.format(output_dir, sub_dir)):
        shutil.copy('{0}/{1}/All/objects.json'.format(output_dir, sub_dir), '{0}/{1}/Export/objects.json'.format(output_dir, sub_dir))
 def test_cv2read(self):
     img = ImageIO.cv2read(self.imageFile)
     tmpImg = cv2.imread(self.imageFile)
     
     equalityBool = (img == tmpImg).all()
     self.assertTrue(equalityBool)
Example #33
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('objects_list', help='List of objects (.json)')
    args = parser.parse_args()

    reader = open(os.path.join(os.environ['FS_ROOT'], args.objects_list), 'rt')
    data = json.load(reader)
    reader.close()
    input_file = data['input_file']
    output_dir = os.path.join(
        os.environ['FS_ROOT'], 'dataset',
        os.path.splitext(os.path.basename(input_file))[0])
    offset = min(
        [data['frames'][f]['frame_id'] for f in range(len(data['frames']))])
    clip = (f + offset) / 900
    if args.objects_list.find('selected') == -1:
        sub_dir = 'clip{0:03d}'.format(clip)
    else:
        sub_dir = 'selected'
    if os.path.isfile('{0}/{1}/All/objects.json'.format(
            output_dir, sub_dir)) and os.path.isfile(
                '{0}/{1}/Export/objects.json'.format(output_dir, sub_dir)):
        return
    elif os.path.isfile('{0}/{1}/All/objects.json'.format(output_dir,
                                                          sub_dir)):
        reader = open('{0}/{1}/All/objects.json'.format(output_dir, sub_dir),
                      'rt')
        data = json.load(reader)
        reader.close()
    else:
        if not os.path.exists('{0}/{1}/All'.format(output_dir, sub_dir)):
            os.makedirs('{0}/{1}/All'.format(output_dir, sub_dir))
        if not os.path.exists('{0}/{1}/Export'.format(output_dir, sub_dir)):
            os.makedirs('{0}/{1}/Export'.format(output_dir, sub_dir))

    if os.path.isfile(os.path.join(os.environ['FS_ROOT'], input_file)):
        cap = cv2.VideoCapture(os.path.join(os.environ['FS_ROOT'], input_file))
        if cap.isOpened() == False:
            print('Cannot open input file: ' +
                  os.path.join(os.environ['FS_ROOT'], input_file))
            exit(1)
        cap.set(cv2.CAP_PROP_POS_FRAMES, offset)
    else:
        filelist = sorted(
            glob.glob(os.path.join(os.environ['FS_ROOT'], input_file,
                                   '*.jpg')))

    for f in range(len(data['frames'])):
        if os.path.isfile(os.path.join(os.environ['FS_ROOT'], input_file)):
            ret, img = cap.read()
        else:
            img = cv2.imread(filelist[f + offset])
            ret = img is not None

        if ret:
            for r in range(len(data['frames'][f]['frame_rois'])):
                #print json.dumps(data['frames'][f]['frame_rois'][r], indent = 4)
                roi = (data['frames'][f]['frame_rois'][r]['roi_x'],
                       data['frames'][f]['frame_rois'][r]['roi_y'],
                       data['frames'][f]['frame_rois'][r]['roi_w'],
                       data['frames'][f]['frame_rois'][r]['roi_h'])
                print roi
                if not os.path.isfile('{0}/{1}/All/objects.json'.format(
                        output_dir, sub_dir)):
                    output = '{0}/{1}/Import/{2}/images/frame{3:06d}/{3:06d}_{4:06d}.jpg'.format(
                        output_dir, sub_dir, data['frames'][f]['frame_rois'][r]
                        ['roi_label']['label_name'],
                        data['frames'][f]['frame_id'],
                        data['frames'][f]['frame_rois'][r]['roi_id'])
                    print output
                    ImageIO.saveImg(output, img, roi)
                    output = '{0}/{1}/All/images/frame{2:06d}/{2:06d}_{3:06d}.jpg'.format(
                        output_dir, sub_dir, data['frames'][f]['frame_id'],
                        data['frames'][f]['frame_rois'][r]['roi_id'])
                    ImageIO.saveImg(output, img, roi)
                if not os.path.isfile('{0}/{1}/Export/objects.json'.format(
                        output_dir,
                        sub_dir)) and data['frames'][f]['frame_rois'][r][
                            'roi_label']['label_name'] != 'Unsorted':
                    output = '{0}/{1}/Export/{2}/{3:06d}_{4:06d}.jpg'.format(
                        output_dir, sub_dir, data['frames'][f]['frame_rois'][r]
                        ['roi_label']['label_name'],
                        data['frames'][f]['frame_id'],
                        data['frames'][f]['frame_rois'][r]['roi_id'])
                    print output
                    ImageIO.saveImg(output, img, roi)
    if not os.path.isfile('{0}/{1}/All/objects.json'.format(
            output_dir, sub_dir)):
        shutil.copy(os.path.join(os.environ['FS_ROOT'], args.objects_list),
                    '{0}/{1}/All/objects.json'.format(output_dir, sub_dir))
    if not os.path.isfile('{0}/{1}/Export/objects.json'.format(
            output_dir, sub_dir)):
        shutil.copy('{0}/{1}/All/objects.json'.format(output_dir, sub_dir),
                    '{0}/{1}/Export/objects.json'.format(output_dir, sub_dir))
Example #34
0
    warped_im1,d1, d2 = registration.registration(im_r.data[0], im_l.data[0], 15,'c')

    tiffLib.imsave(outputPath + 'warped_im1.tif',np.float32(warped_im1))
    tiffLib.imsave(outputPath + 'd1.tif',np.float32(d1))
    tiffLib.imsave(outputPath + 'd2.tif',np.float32(d2))
    '''

    ############################# comparision test #####################################
    
    dataPath = 'C:/Tomosynthesis/localtest/reg/'
    outputPath = 'C:/Tomosynthesis/localtest/reg/'

    fileName_r = 'op.tif'
    fileName_l = '6044_l.tif'

    im_r = ImageIO.imReader(dataPath,fileName_r, 'tif',2)
    im_l = ImageIO.imReader(dataPath,fileName_l, 'tif',2)

    params = []
    params.append(('1d', 'cv_comp', cv.CV_COMP_CORREL))
    params.append(('1d', 'scipy_comp', 'Euclidean'))
    params.append(('1d', 'scipy_comp', 'Manhattan'))
    params.append(('1d', 'kl_div', 'None'))

    params.append(('2d', cv.CV_TM_SQDIFF_NORMED, 'None'))
    params.append(('2d', cv.CV_TM_CCORR_NORMED, 'None'))
    params.append(('2d', cv.CV_TM_CCOEFF_NORMED, 'None'))

    params.append(('decomp', 'eigen', 'None'))
    params.append(('decomp', 'NMF', 'None'))
sys.path.append('../Modules/')
import cv2
import ImageIO
import Normalization
from matplotlib import pyplot as plt
import numpy

'''
A test program to make sure that the Normalization methods work.

This normalizes the images, and displays them.
'''

#test = 'test.jpg'
test = "/home/redwards/Dropbox/ComputerVision/TestCode/test.png"
im = ImageIO.cv2read(test)
print im.shape


print "Testing Tylers normalization"
tn = Normalization.Tyler(im)

print "Testing histogram equalization"
he = Normalization.equalizeHistograms(im)
heo = numpy.ones_like(im)
heo[:,:,0]=he
heo[:,:,1]=he
heo[:,:,2]=he

print "Simple normaliztion"
nh = Normalization.simpleNorm(im)
 def setUp(self):
     imageFile = '../test/test.jpg'
     self.img = ImageIO.cv2read(imageFile)
     self.contours = contours(self.img)
import sys
sys.path.append('../Modules/')
import ImageIO
from Analysis import *

'''
A simple test whether the bgr_energy calculation works
'''

im = sys.argv[1]

img = ImageIO.cv2read(im)
fft=FFT()
for i in range(3):
    print "The energy for the ", i, " channel is ", fft.energy(img[:,:,i])

def imageWriter(images,seen,args,fout,classification,stats,fft,lap,edge):
    for imgfile in images:

        if imgfile in seen: continue

        if os.path.isdir(os.path.join(args.directory, imgfile)):
            temp = os.listdir(os.path.join(args.directory, imgfile))
            for f in temp:
                images.append(os.path.join(imgfile, f))
            continue
        
        #rewrite of above if statement
        #if os.path.isdir(os.path.join(args.directory,imgfile)):
        #    temp = os.listdir(os.path.join(args.directory,imgfile))
        #    pool = Pool()
        #    pool.map(images.append, os.path.join(imgfile, f))
        #    pool.close()
        #    pool.join()
        #    continue
            

        if not args.all and imgfile not in classification:
            continue

        # silently skip the bin files that have the gps data
        if imgfile.endswith('bin'):
            continue
        # alert to other files that were skipped
        if not (imgfile.endswith('png') | imgfile.endswith('jpg')):
            sys.stderr.write("Skipped file: " + imgfile + "\n")
            continue

        if args.verbose:
            sys.stderr.write("Parsing " + imgfile + "\n")

        fout.write( imgfile + "\t" )
        if imgfile in classification:
            fout.write( classification[imgfile] + "\t")
        else:
            fout.write( "unknown\t" )

        img = ImageIO.cv2read(os.path.join(args.directory, imgfile))
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        fout.write( ('\t'.join(map(str, [stats.min(gray), stats.max(gray), stats.median(gray), stats.mean(gray)]))) + "\t" )

        ngray = Normalization.equalizeHistograms(gray)
        # apply a gaussian blur to remove edge effects
        ngray = cv2.GaussianBlur(ngray, (3,3), 0)
        fout.write( ('\t'.join(map(str, [stats.min(ngray), stats.max(ngray), stats.median(ngray), stats.mean(ngray)]))) + "\t")

        for i in range(3):
            imp = img[:,:,i]
            fout.write( ('\t'.join(map(str, [stats.min(imp), stats.max(imp), stats.median(imp), stats.mean(imp)]))) + "\t" )
        fout.write( str(fft.energy(gray)) + "\t" + str(fft.energy(ngray)) + "\t")

        if args.features:
            feats.detect_kp_ORB(ngray)
            fout.write( str(feats.numberKeyPoints()) + "\t" + str(feats.medianKeyPointSize()) + "\t" + str(feats.meanKeyPointSize()) + "\t")

            for i in range(15):
                fout.write( str(feats.numKeyPoints(i*10)) + "\t")
        else:
            fout.write("0\t0\t0\t");
            for i in range(15):
                fout.write("0\t")
    
        for i in range(15):
            k=2*i+1
            fout.write( str(lap.sum(ngray, k)) + "\t")

        for i in range(25):
            t2 = 10*i
            fout.write( str(edge.sumCanny(ngray, 1, t2)) + "\t")
        #edge.sumCanny(gray)

        # Contour detection
        ctr = Contours.contours(ngray)
        for i in range(5):
            threshold=50*i
            ctr.withCanny(1, threshold)
            if ctr.numberOfContours() == 0:
                fout.write( "0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t" )
            else:
                try:
                    fout.write( "\t".join(map(str, [ctr.numberOfContours(), ctr.numberOfClosedContours(),
                                          ctr.numberOfOpenContours(), ctr.totalContourArea(), cv2.contourArea(ctr.largestContourByArea()),
                                          ctr.totalPerimeterLength()])) + "\t")
                    ctr.linelengths()
                    fout.write( "\t".join(map(str, [ctr.maxLineLength(), ctr.meanLineLength(), ctr.medianLineLength(), ctr.modeLineLength()])) + "\t")
                except Exception as e:
                    sys.stderr.write("There was an error calculating the contours for " + imgfile +": " + e.message + "\n")
                    fout.write( "0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t" )

        fout.write("\n")    
Example #39
0
 def __init__(self):
     self.iio = IIO.ImageIO("test.png", "test_o.png")
     self.image = None
     self.result = None
     self.cwd = os.getcwd()
     self.ui = UI.UI(self)
Example #40
0
def creatTrainigSam(dataPath, opt = 'all', iRnum = 6,iSnum = 12, gRnum = 4,gSnum = 12):
    """ Creat training samples(2D) and compute features for each training sample 

    Parameters
    ----------
    dataPath: str
        The directory where training image ROIs are stores.
    opt: str
        Options for compute features.
    iRnum: integer
        The number of rings to be divided in computing intensity features
    iSnum: integer
        The number of sectors to be divided in computing intensity features
    gRnum: integer
        The number of rings to be divided in computing gradient features
    gSnum: integer
        The number of sectors to be divided in computing gradient features
    """

    file_list = os.listdir(dataPath)
    int_feats = np.zeros((len(file_list),4),np.double)
    gr_feats = np.zeros((len(file_list),4),np.double)
    seg_feats = np.zeros((len(file_list),7),np.double)
    all_feats = np.zeros((len(file_list),15),np.double)

    LightPatchList = []
    counter = 0
    for fil in file_list:
        im = ImageIO.imReader(dataPath, fil,'tif',2)

        # Calculating intensity features
        if opt == 'Int' or opt == 'all':
            patch = TPatch.TPatch()
            patch.initialize(im.data[0])
            int_feats[counter,:] = patch.getIntenfeats(iRnum,iSnum)

        # Calculating gradient features
        if opt == 'Grad' or opt == 'all':
            # preprocess
            im.downSample(rate = 2)
            eqimg = histEqualization.histEqualization(im.sampled_data[0], 16)
            smoothimg = filters.gaussian_filter(eqimg, sigma = 2, order=0, output=None, mode='reflect', cval=0.0, truncate=4.0)

            patch = TPatch.TPatch()
            patch.initialize(smoothimg)
            gr_feats[counter,:] = patch.getGradfeats(gRnum,gSnum)

        # Calculating segment features
        if opt == 'seg' or opt == 'all':
            
            patch = TPatch.TPatch()
            patch.initialize(im.data[0])
            seg_feats[counter,:] = patch.getSegmentFeats()

        if opt == 'all':
            all_feats[counter,:] = np.hstack((int_feats[counter,:], gr_feats[counter,:], seg_feats[counter,:]))

            lightPatch = TPatch.TLightPatch()
            lightPatch.pdata = im.data[0]
            lightPatch.feats = all_feats[counter,:]
            lightPatch.patch_center = (im.data[0].shape[0]/2, im.data[0].shape[1]/2)
            LightPatchList.append(lightPatch)

        counter = counter + 1
        
    if opt == 'all':
        return LightPatchList

    if opt == 'Int':
        return int_feats
    if opt == 'Grad':         
        return gr_feats

    if opt == 'seg':
        return seg_feats
Example #41
0
import ScaleSpace as scale_space
import ImageIO as io
import LoG as log
octaves = scale_space.getOctaves()

for li in octaves:
    for x in li:
        io.showImage(x)
        print(x)

log.calculateLoG(octaves)
Example #42
0
                        for n in range(y - 1, y + 2):
                            if ary[n, m] == 255:
                                num = num + 1
                                ary[n, m] = 0
                                group[n, m] = val
                                q.append((m, n))
                fea.append(num)
    com = 0
    pos = 0
    for k in range(len(fea)):
        if fea[k] >= com:
            com = fea[k]
            pos = k
    for i in range(L):
        for j in range(W):
            if group[j, i] == pos + 1:
                ary[j, i] = 255
    ary = dilation(dilation(ary))
    ary = erosion(erosion(ary))
    ary = gradient(ary)

    return ary


if __name__ == "__main__":
    iio = IIO.ImageIO()
    arr = iio.get_input_image("img/I0071695_1.jpg", "L")
    ans = run(arr, 205, 380, 170, 325)
    plt.imshow(ans)
    plt.show()
Example #43
0
''' A test suite written to test the image analysis code. 

All of these tests should pass'''

import sys
sys.path.append('../Modules/')
import ImageIO
from Analysis import *
import os

imageFile = 'test.jpg'
if not os.path.exists(imageFile):
    sys.stderr.write("The test image file " + imageFile + " does not exist! Can't complete tests");
    sys.exit(-1)

image = ImageIO.cv2read(imageFile)
grayscale = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

# test the statistics module

print "The following tests are performed on the grayscale image:"
print "\nTesting the stats class"
s=Stats()
print "Testing minimum: ", s.min(grayscale)
print "Testing maximum: ", s.max(grayscale)
print "Testing mean: ", s.mean(grayscale)
print "Testing median: ", s.median(grayscale)

print "\nTesting the fft class"
f=FFT()
print "Testing FFT: "
Example #44
0
# encoding: utf-8
import tensorflow as tf
import numpy as np
import DataModel
from DataModelSet import DataModelSet
import ImageIO
from HedNetModel import HedNetModel

print "start run..."
filename = "train_data/image_label.csv"

dataModelSet = DataModelSet(ImageIO.read_image_label_model_file(filename))
print "num_examples : %d" % (dataModelSet.num_examples)

for x in xrange(1, 10):
    dataModelpart = dataModelSet.next_batch(5)
    for dataModel in dataModelpart:
        dataModel.discription()

print "stop run..."
import cv2
import ImageIO as io
import math

img =io.getImage("test2.jpg")
Octaves=[]
io.showImage(img)
b= 1/2
for x in range(4):
    List = []
    a=b
    for y in range(5):
        a = a* math.sqrt(2)
        List.append(cv2.GaussianBlur(img, (5, 5), sigmaX=a, sigmaY=0, borderType=1))
    b*=2
    Octaves.append(List)
    height, width = img.shape[:2]
    img = cv2.resize(img, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_AREA)

def getOctaves():
    return Octaves
            test_correct = 0
            for i in trange(len(test_x), ascii=True):
                test_correct = test_correct + accuracy.eval(
                    feed_dict={
                        x: test_x[i].reshape((1, 64, 64)),
                        y_: test_y[i].reshape((1, 28)),
                        keep_prob: 1.
                    })
            test_accuracy = test_correct / len(test_x)
            print('the accuracy in fake test set:{}'.format(test_accuracy))
            print('*' * 40)


if __name__ == "__main__":
    if (sys.argv[1] == 'train'):
        x_train_use_ori, y_train_use_ori, x_valid_use_ori, y_valid_use_ori, ori_test_x, ori_test_y = ImageIO.loadTrainImage(
            0.1, False)
        '''print(x_train_use_ori.shape)
        print(y_train_use_ori.shape)
        print(x_valid_use_ori.shape)
        print(y_valid_use_ori.shape)
        print(ori_test_x.shape)
        print(ori_test_y.shape)'''
        model(x_train_use_ori,
              y_train_use_ori,
              x_valid_use_ori,
              y_valid_use_ori,
              ori_test_x,
              ori_test_y,
              mode='train')
    elif (sys.argv[1] == 'test'):
        x_train_use_ori, y_train_use_ori, x_valid_use_ori, y_valid_use_ori, ori_test_x, ori_test_y = ImageIO.loadTrainImage(
def model(model_x, model_y, valid_x, valid_y, test_x, test_y, mode='train'):
    x = tf.placeholder(np.float32, [None, 64, 64])
    y_ = tf.placeholder(tf.float32, [None, 68])
    x_image = tf.reshape(x, [-1, 64, 64, 1])

    W_conv1 = weight_variable([3, 3, 1, 16])
    b_conv1 = bias_variable([16])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # 64*64*16

    W_conv1_1 = weight_variable([3, 3, 16, 32])
    b_conv1_1 = bias_variable([32])
    h_conv1_1 = tf.nn.relu(conv2d(h_conv1, W_conv1_1) + b_conv1_1)  # 64*64*32
    h_pool1 = max_pool_2x2(h_conv1_1)  # 32*32*32

    W_conv2 = weight_variable([3, 3, 32, 48])
    b_conv2 = bias_variable([48])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  # 32*32*48

    W_conv2_1 = weight_variable([3, 3, 48, 64])
    b_conv2_1 = bias_variable([64])
    h_conv2_1 = tf.nn.relu(conv2d(h_conv2, W_conv2_1) + b_conv2_1)  # 32*32*64
    h_pool2 = max_pool_2x2(h_conv2_1)  # 16*16*64

    W_conv3 = weight_variable([3, 3, 64, 128])
    b_conv3 = bias_variable([128])
    h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)  # 16*16*128

    W_conv3_1 = weight_variable([3, 3, 128, 256])
    b_conv3_1 = bias_variable([256])
    h_conv3_1 = tf.nn.relu(conv2d(h_conv3, W_conv3_1) + b_conv3_1)  # 16*16*256
    h_pool3 = max_pool_2x2(h_conv3_1)  #8*8*256

    W_fc1 = weight_variable([8 * 8 * 256, 2048])
    b_fc1 = bias_variable([2048])
    h_pool2_flat = tf.reshape(h_pool2, [-1, 8 * 8 * 256])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

    keep_prob = tf.placeholder(tf.float32)
    h_fc1_dropout = tf.nn.dropout(h_fc1, keep_prob)

    W_fc2 = weight_variable([2048, 68])
    b_fc2 = bias_variable([68])
    y_conv = tf.matmul(h_fc1_dropout, W_fc2) + b_fc2

    cross_entropy = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
    train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
    accuracy = tf.reduce_mean(
        tf.cast(tf.equal(tf.argmax(y_, 1), tf.argmax(y_conv, 1)), tf.float32))
    mark = tf.argmax(y_conv, 1)

    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        saver = tf.train.Saver(max_to_keep=100)
        # saver = tf.train.import_meta_graph('./my_net/epoch_18.ckpt.meta')
        if (mode == 'train'):
            batch_size = 32
            for epoch in range(30):
                get_batch = my_batch(model_x, model_y, batch_size)
                for i in range(len(model_x) // batch_size):
                    x_batch, y_batch = next(get_batch)
                    x_batch = ImageIO.shift_images(x_batch)
                    _, myloss, train_accuracy = sess.run(
                        [train_step, cross_entropy, accuracy],
                        feed_dict={
                            x: x_batch,
                            y_: y_batch,
                            keep_prob: 0.5
                        })
                    if i % 25 == 0:
                        print(
                            'epoch {} setp {},the train accuracy: {},the loss: {}'
                            .format(epoch, i, train_accuracy, myloss))
                    # train_step.run(feed_dict = {x: x_batch, y_: y_batch, keep_prob: 0.5})
                print('*' * 40)
                test_correct = 0.0
                for i in trange(len(valid_x), ascii=True):
                    test_correct = test_correct + accuracy.eval(
                        feed_dict={
                            x: valid_x[i].reshape((1, 64, 64)),
                            y_: valid_y[i].reshape((1, 68)),
                            keep_prob: 1.
                        })
                test_accuracy = round(test_correct / len(test_x), 4)
                print('epoch {},the accuracy in valid set:{}'.format(
                    epoch, test_accuracy))
                print('*' * 40)
                test_correct = 0.0
                for i in trange(len(test_x), ascii=True):
                    test_correct = test_correct + accuracy.eval(
                        feed_dict={
                            x: test_x[i].reshape((1, 64, 64)),
                            y_: test_y[i].reshape((1, 68)),
                            keep_prob: 1.
                        })
                test_accuracy = round(test_correct / len(test_x), 4)
                print('epoch {},the accuracy in test set:{}'.format(
                    epoch, test_accuracy))
                print('*' * 40)
                path = saver.save(sess, './my_net/epoch_{}.ckpt'.format(epoch))
                print('save path: {}'.format(path))
        elif (mode == 'test'):
            ckpt = tf.train.get_checkpoint_state("./my_net")
            if ckpt and ckpt.model_checkpoint_path:
                saver.restore(sess, ckpt.model_checkpoint_path)
            print('*' * 40)
            test_correct = 0
            for i in trange(len(test_x), ascii=True):
                test_correct = test_correct + accuracy.eval(
                    feed_dict={
                        x: test_x[i].reshape((1, 64, 64)),
                        y_: test_y[i].reshape((1, 28)),
                        keep_prob: 1.
                    })
            test_accuracy = test_correct / len(test_x)
            print('the accuracy in fake test set:{}'.format(test_accuracy))
            print('*' * 40)
Example #48
0
    # Mandatory fields
    parser.add_argument("filename", help="The filename of the input picture")
    parser.add_argument("output", help="The filename of the output picture")
    # Available parameters
    parser.add_argument("--brightness", metavar='amount', type=int)
    parser.add_argument("--contrast", metavar='amount', type=float)
    parser.add_argument("--gamma", metavar='amount', type=float)
    parser.add_argument("--histogramEQ", type=bool)
    parser.add_argument("--histogramMatch", type=str)
    parser.add_argument("--saturation",
                        metavar='amount',
                        type=float,
                        help="From -1 to 1")
    args = parser.parse_args()

    img_arr = ImageIO.load_image(args.filename)
    if args.brightness:
        img_arr = change_brightness(img_arr, args.brightness)
    if args.contrast:
        img_arr = change_contrast(img_arr, args.contrast)
    if args.gamma:
        img_arr = change_gamma(img_arr, args.gamma)
    if args.histogramEQ:
        img_arr = histogram_equalization(img_arr)
    if args.histogramMatch:
        target_arr = ImageIO.load_image(args.histogramMatch)
        img_arr = histogram_matching(img_arr, target_arr)
    if args.saturation:
        img_arr = change_saturation(img_arr, args.saturation)

    ImageIO.save_image(args.output, img_arr)
Example #49
0
def graphrepresentation(myarray,im):
    '''creating a graph and add images in tiff image as nodes of graphs  '''
    G=nx.Graph()
    Size=myarray.shape
    a=Size[0]
    for i in range(0,a-1):
        G.add_node(i,point=myarray[i])
        
    #G.add_nodes_from(im)
    
    #G.add_nodes_from(myarray)
    '''after create graph we should add edges and weight to edges by mutual information  '''
    numberofedges=myarray.shape[0]
    
    
    for i in range (myarray.shape[0]):
        sum=0  
        path='/Users/Shared/TomosynthesisData/processed/5039/'
        fileName='5039.tif'
        fileName = fileName.split('.')
        fileName = fileName[0] + str(i) + '.tif'
        im1 = ImageIO.imReader(path,fileName,'tif',2)
        for j in range(myarray.shape[0]):
            G.add_edge(i,j)
            #im1=im[i]
            fileName='5039.tif'
            fileName = fileName.split('.')
            fileName = fileName[0] + str(j) + '.tif'
            im2 = ImageIO.imReader(path,fileName,'tif',2)
            
            '''finding mutual information of different features then add them for finding weight'''
            feature1=waveletcLBP.concatinationhist(im1.data[0])
            feature2=waveletcLBP.concatinationhist(im2.data[0])
            weight=weightinginfo(feature1,feature2,im1,im2)
            sum=sum+weight
            
            feature1=RBST.shortrunfacility(im1.data[0],im1.data[0])
            feature2=RBST.shortrunfacility(im2.data[0],im2.data[0]) 
            weight=weightinginfo(feature1,feature2,im1,im2)
            
            
            print len(feature1), len(feature2)
            
            
            feature1=RBST.shortrunfacility(im1.data[0],im1.data[0])
            feature2=RBST.shortrunfacility(im2.data[0],im2.data[0]) 
            weight=weightinginfo(feature1,feature2,im1,im2)
            sum=sum+weight
            
            G.add_weighted_edges_from([i,j,sum])
            
    listpath=longest_path(G)
    "after finding longest we can combine features with the weighting list and order in list"
    lengthlist=len(listpath)       
    for i in range(lengthlist-1):
        a=listpath(i)
        b=listpath(i+1)
        weightonthelist=G.adjacency_ite(a,b)
        weightlist=list.append(weightonthelist)
    return weightlist, listpath    
        
            
             
        
        
    
    
     
    
    
    
    
 def test_cv2grayscale(self):
     imgGray = ImageIO.cv2grayscale(self.imageFile)
     tmpImgGray = cv2.imread(self.imageFile)
     tmpImgGray = cv2.cvtColor(tmpImgGray,cv2.COLOR_BGR2GRAY)
     equalityBool = (imgGray == tmpImgGray).all()
     self.assertTrue(equalityBool)
Example #51
0
                    this_color += region[r_t, c_t, :] * coefs[r_t, c_t]
            this_color = np.minimum(np.maximum(this_color, 0), 255)
            output[r, c, :] = this_color
        print("\rPlease Wait: %d / %d" % (r, target_r), end='')
    return output


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Mandatory fields
    parser.add_argument("filename", help="The filename of the input picture")
    parser.add_argument("output", help="The filename of the output picture")
    parser.add_argument("method", type=str, help="nn, bi, cu or la")
    parser.add_argument("r", type=int, help="height")
    parser.add_argument("c", type=int, help="width")
    args = parser.parse_args()

    img_arr = ImageIO.load_image(args.filename)
    if args.method == "nn":
        img_arr = nearest_neighbour_resampling(img_arr, args.r, args.c)
    elif args.method == "bi":
        img_arr = bilinear_resampling(img_arr, args.r, args.c)
    elif args.method == "cu":
        img_arr = bicubic_resampling(img_arr, args.r, args.c)
    elif args.method == "la":
        img_arr = lanczos_resampling(img_arr, args.r, args.c)
    else:
        print("Resampling method not supported. Try nn, bi, cu or la.")

    ImageIO.save_image(args.output, img_arr)
 def setUp(self):
     imageFile = '../test/test.jpg'
     self.img = ImageIO.cv2read(imageFile)
        for f in temp:
            images.append(os.path.join(imgfile, f))
        continue

    # silently skip the bin files that have the gps data
    if imgfile.endswith('bin'):
        continue
    # alert to other files that were skipped
    if not (imgfile.endswith('png') | imgfile.endswith('jpg')):
        sys.stderr.write("Skipped file: " + imgfile + "\n")
        continue

    if args.verbose:
        sys.stderr.write("Parsing " + imgfile + "\n")

    fout.write( imgfile + "\t" )
    
    img = ImageIO.cv2read(os.path.join(args.directory, imgfile))
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ngray = Normalization.equalizeHistograms(gray)
    ngray = cv2.GaussianBlur(ngray, (3,3), 0)

    feats.detect_kp_ORB(ngray)
    fout.write( str(feats.numberKeyPoints()) + "\t" + str(feats.medianKeyPointSize()) + "\t" + str(feats.meanKeyPointSize()) )

    for i in range(15):
        fout.write("\t" + str(feats.numKeyPoints(i*10)))
    fout.write("\n")


Example #54
0
 def threshold(self, img):
     img = ImageIO.grayscale(img)
     ret, thresh = cv2.threshold(gray, 0, 255,
                                 cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
     return thresh