Exemplo n.º 1
0
 def _execute(self,x):
     x = x.astype(np.float32)
     x = x / ( np.mean( cv2.pow(np.abs(x), self.alpha) ) ** (1/self.alpha) + 1e-6)
     absx = np.abs(x)
     x = x / ( np.mean( cv2.pow(np.choose(absx > self.tau,(self.tau,absx)), self.alpha ) ) ** (1/self.alpha) + 1e-6 )
     x = self.tau * np.tanh( x / self.tau )
     return x
Exemplo n.º 2
0
 def __calc_gradient_image(self, img, image_depth=cv2.CV_8UC1):
     deriv_img = cv2.GaussianBlur(img, self.__gauss_kernel_size, self.__gauss_sigma)
     sx = cv2.Sobel(deriv_img, image_depth, 1, 0, ksize=self.__ksize_gradient)
     sy = cv2.Sobel(deriv_img, image_depth, 0, 1, ksize=self.__ksize_gradient)
     self.__deriv_img = cv2.sqrt(cv2.add(cv2.pow(sx, 2), cv2.pow(sy, 2)))
     # self.__deriv_img = cv2.Laplacian(deriv_img, image_depth, ksize=self.__ksize_gradient)
     return self.__deriv_img
Exemplo n.º 3
0
def getGradientImageInfo(gray):
	temp1=gray
	gx=np.array(0)
	gy=np.array(0)
	gd=gray
	gm=gray
	gx=cv2.Sobel(temp1, cv2.CV_16S, 1, 0, gx, 3, 1, 0, cv2.BORDER_DEFAULT)
	gy=cv2.Sobel(temp1, cv2.CV_16S, 0, 1, gy, 3, 1, 0, cv2.BORDER_DEFAULT)
	gm=cv2.add(cv2.pow(gx, 2), cv2.pow(gy, 2))		
	gm=pylab.sqrt(gm) 
	gd=cv2.add(np.arctan(gx), np.arctan(gy))*(180/math.pi)
	resolution=5
	gx=gx[::resolution*-1,::resolution]
	gy=gy[::resolution*-1,::resolution]
	gm=gm[::resolution*-1,::resolution]
	gd=gd[::resolution*-1,::resolution]
	X,Y = np.meshgrid( np.arange(0,2*math.pi,.2),np.arange(0,2*math.pi,.2))
	U = pylab.cos(X)
	V = pylab.sin(Y)
	q=matplotlib.pyplot.quiver(gx,gy)
#	key=matplotlib.pyplot.quiverkey(q, 1, 1, 5, 'test', coordinates='data', color='b')
	#matplotlib.pyplot.show()
	matplotlib.pyplot.close()
	#cv2.imshow('gd', gd)
	return gx,gy,gm,gd, resolution
Exemplo n.º 4
0
def Pyramid(img):
	YUV = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
	YUV = cv2.resize(YUV,(40,40))
	Y,U,V = cv2.split(YUV)
	YUV = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
	img = cv2.resize(YUV,(26,26))
	kernel1 = np.ones((3,1),np.float32)
	kernel2 = np.ones((1,3),np.float32)
	kernel1[0] = -1
	kernel1[1] = 0
	kernel2[0] = [-1,0,1]
	dst = cv2.filter2D(img,cv2.CV_16S,kernel1)
	dstv1 = np.int16(dst)
	dstv2 = cv2.pow(dstv1,2)
	dst = cv2.filter2D(img,cv2.CV_16S,kernel2)
	dsth1 = np.int16(dst)
	dsth2 = cv2.pow(dsth1,2)
	dst1 = dsth2 + dstv2
	dst1 = np.float32(dst1)
	dstfinal = cv2.sqrt(dst1).astype(np.uint8)
	finalh =  dsth1
	finalv = dstv1
	finalm = dstfinal
	UporDown = (finalv > 0 ).astype(int)
	LeftorRight = 2*(finalh > 0).astype(int)
	absh = map(abs, finalh)
	absv = map(abs, finalv)
	absv[:] = [x*1.732 for x in absv]
	absh = np.float32(absh)
	absv = np.float32(absv)
	high = 4*(absv > absh).astype(int)
	out = high + LeftorRight + UporDown
	features = []
	for x in range(6):
		hrt = np.zeros(out.shape[:2],np.uint8)
		features.append(hrt)
	for x in range(out.shape[:2][0]):
		for y in range(out.shape[:2][1]):
			z = out[x][y]
			if z == 4 or z == 6:
#				print "a",z
				features[4][x][y] = finalm[x][y]
			elif z == 5 or z == 7:
				features[5][x][y] = finalm[x][y]
#				print "b",z
			else:
				features[z][x][y] = finalm[x][y]
#				print z
	kernelg1 = 0.125*np.ones((4,4),np.float32)
	kernelg2 = 0.25*np.ones((2,2),np.float32)
	lastFeatures = []	
	for img in features:
		tote = cv2.sumElems(img)
		tote = tote/img.size
		img = img/tote
		print img
		print cv2.sumElems(img)
		print img.size
		lastFeatures.append(img1)
	return lastFeatures
Exemplo n.º 5
0
def tantriggs(image):
    # Convert to float
    image = np.float32(image)

    image = cv2.pow(image, GAMMA)
    image = difference_of_gaussian(image)

    # mean 1
    tmp = cv2.pow(cv2.absdiff(image, 0), ALPHA)
    mean = cv2.mean(tmp)[0]
    image = cv2.divide(image, cv2.pow(mean, 1.0/ALPHA))

    # mean 2
    tmp = cv2.pow(cv2.min(cv2.absdiff(image, 0), TAU), ALPHA)
    mean = cv2.mean(tmp)[0]
    image = cv2.divide(image, cv2.pow(mean, 1.0/ALPHA))

    # tanh
    exp_x = cv2.exp(cv2.divide(image, TAU))
    exp_negx = cv2.exp(cv2.divide(-image, TAU))
    image = cv2.divide(cv2.subtract(exp_x, exp_negx), cv2.add(exp_x, exp_negx))
    image = cv2.multiply(image, TAU)

    image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8UC1)

    return image
Exemplo n.º 6
0
def curvature_central(u):
    u=np.float32(u)
    u_x,u_y=np.gradient(u)
    norm=cv2.pow(np.power(u_x,2)+cv2.pow(u_y,2)+1E-10,0.5)
    N_x=cv2.divide(u_x,norm)
    N_y=cv2.divide(u_y,norm)
    N_xx,junk=np.gradient(N_x)
    junk,N_yy=np.gradient(N_y)
    return np.float32(N_xx+N_yy)
Exemplo n.º 7
0
 def expProcessing(self, sourceImg):
     # kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (11,11))
     # closed = cv2.morphologyEx(binaryImg, cv2.MORPH_CLOSE, kernel1)
     # div = np.float32(binaryImg)/(closed)
     # binaryImg = np.uint8(cv2.normalize(div, div, 0, 255, cv2.NORM_MINMAX))
     # res2 = cv2.cvtColor(res, cv2.COLOR_GRAY2BGR)
     gammaImg = sourceImg.copy()
     cv2.cv.ConvertScale(cv2.cv.fromarray(gammaImg), cv2.cv.fromarray(gammaImg), 1.0 / 255, 0)
     cv2.pow(gammaImg, self.gammaCorrectionVal, gammaImg)
     return binaryImg
Exemplo n.º 8
0
Arquivo: gamma.py Projeto: hasin89/mgr
def correction(gray, gammaFactor):
    u"""
    skala szarości
    :param gray:
    :param gammaFactor:
    :return:
    """
    gamma_correction = 1.0 / gammaFactor

    img_tmp = gray / 255.0
    cv2.pow(img_tmp, gamma_correction, img_tmp)
    img_gamma = img_tmp * 255.0

    # zamiana na int
    img_result = np.array(img_gamma, 'uint8')
    return img_result
Exemplo n.º 9
0
def pycv_power(arr, exponent):
    """Raise the elements of a floating point matrix to a power. 
    It is 3-4 times faster than numpy's built-in power function/operator."""
    if arr.dtype not in [numpy.float32, numpy.float64]:
        arr = arr.astype('f')
    if arr.flags['C_CONTIGUOUS'] == False:
        arr = numpy.ascontiguousarray(arr)        
    return cv2.pow(arr, exponent)
Exemplo n.º 10
0
def gammaCorrection(filename, pow_value=3):
	img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)

	transformed = img / 255.0
	transformed = cv2.pow(transformed, pow_value)
	transformed = np.uint8(transformed*255)

	return [img, transformed]
Exemplo n.º 11
0
 def save2jpg(self,fout):
     img8 = numpy.zeros((self.width,self.height,3),dtype= numpy.uint8)
     img = cv2.pow(self.img,1/2.2)
     cv2.convertScaleAbs(img,img8,256)
     proxy = cv2.resize(img8, (1280, 720), interpolation=cv2.INTER_AREA)
     #cv2.putText(proxy, "HELLO", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255),2)
     print "saving image: " + fout
     cv2.imwrite(fout, proxy)
     return "saving image: " + fout
Exemplo n.º 12
0
def farthest_point(defects, contour, centroid):
	s = defects[:,0][:,0]
	cx, cy = centroid
	
	x = np.array(contour[s][:,0][:,0], dtype=np.float)
	y = np.array(contour[s][:,0][:,1], dtype=np.float)
				
	xp = cv2.pow(cv2.subtract(x, cx), 2)
	yp = cv2.pow(cv2.subtract(y, cy), 2)
	dist = cv2.sqrt(cv2.add(xp, yp))

	dist_max_i = np.argmax(dist)

	if dist_max_i < len(s):
		farthest_defect = s[dist_max_i]
		farthest_point = tuple(contour[farthest_defect][0])
		return farthest_point
	else:
		return None	
Exemplo n.º 13
0
def getGradientImageInfo(I):
	g_x = cv2.Sobel(I, cv.CV_64F, 1,0)
	g_y = cv2.Sobel(I, cv.CV_64F, 0,1) # ksize=3 som **kwargs

	X,Y = I.shape
	orientation = np.zeros(I.shape)
	magnitude = np.zeros(I.shape)
	sq_g_x = cv2.pow(g_x, 2)
	sq_g_y = cv2.pow(g_y, 2)
	fast_magnitude = cv2.pow(sq_g_x + sq_g_y, .5)

	# for x in range(X):
	# 	for y in range(Y):
	# 		orientation[x][y] = np.arctan2(g_y[x][y], g_x[x][y]) * (180 / math.pi)
	# 		magnitude[x][y] = math.sqrt(g_y[x][y] ** 2 + g_x[x][y] ** 2)


	#print fast_magnitude[0]
	#print magnitude[0]

	return fast_magnitude,orientation
Exemplo n.º 14
0
    def gammaCorrection(self, img):
        hsvArray = cv2.split(img)
        val = hsvArray[2]
        correction = 0.2
        inverse_gamma = 1.0 / correction
        val = val / 255.0
        val = cv2.pow(val, inverse_gamma)
        val = np.uint8(val * 255.0)
        hsvArray[2] = val

        img = cv2.merge((hsvArray))
        return img
Exemplo n.º 15
0
def imcv2_recolor(im, a = .1):
	t = [np.random.uniform()]
	t += [np.random.uniform()]
	t += [np.random.uniform()]
	t = np.array(t) * 2. - 1.

	# random amplify each channel
	im = im * (1 + t * a)
	mx = 255. * (1 + a)
	up = np.random.uniform() * 2 - 1
# 	im = np.power(im/mx, 1. + up * .5)
	im = cv2.pow(im/mx, 1. + up * .5)
	return np.array(im * 255., np.uint8)
Exemplo n.º 16
0
 def save2Thumbnail(self,fout):
     Tb = numpy.zeros((256,256,3),dtype= numpy.uint8)
     img8 = numpy.zeros((self.width,self.height,3),dtype= numpy.uint8)
     img = cv2.pow(self.img,1/2.2)
     cv2.convertScaleAbs(img,img8,256)
     big = max(self.width,self.height)
     small = min(self.width,self.height)
     scale = float(big)/float(small)
     newSize =  int(256 / scale)
     thumbnail = cv2.resize(img8, (256,newSize), interpolation=cv2.INTER_AREA)
     h, w = thumbnail.shape[:2]
     s =  int((256-h)/2.0)
     Tb[s:256-s,:,:] = thumbnail[:,:,:]
     cv2.imwrite(fout, Tb)
Exemplo n.º 17
0
def light_normalization(img):
    """
        Normalizes light conditions in the given B&W image
    """
    #Histogram equalization
    img = cv.equalizeHist(img)
    #Gamma correction with factor 0.8 (smaller factors -> more bright)
    img = img/255.0
    img = cv.pow(img,0.8)
    img = np.uint8(img*255)
    img = cv.fastNlMeansDenoising(img,10,10,7,21)
    #Gaussian filter to smooth
    img = cv.GaussianBlur(img,(3,3),0)
    return img
Exemplo n.º 18
0
def generateNewColor(img):
    b,g,r = cv2.split(img)
    c1 = VUtil.toBGR(np.uint8(np.arctan2(r,np.maximum(b,g))*255), 'gray')
    c2 = VUtil.toBGR(np.uint8(np.arctan2(g,np.maximum(r,b))*255), 'gray')
    c3 = VUtil.toBGR(np.uint8(np.arctan2(b,np.maximum(r,g))*255), 'gray')
    denominator = cv2.pow(r-g,2)+cv2.pow(r-b,2)+cv2.pow(g-b,2)
    l1 = VUtil.toBGR(cv2.pow(r-g,2)/denominator, 'gray')
    l2 = VUtil.toBGR(cv2.pow(r-b,2)/denominator, 'gray')
    l3 = VUtil.toBGR(cv2.pow(g-b,2)/denominator, 'gray')
    return np.vstack((np.hstack((c1,c2,c3)),np.hstack((l1,l2,l3))))
Exemplo n.º 19
0
def GammaCorrection(img, correction):
    """            
    Function definition
    +++++++++++++++++++
            
        .. py:function:: GammaCorrection(img, correction)

            Apply gamma correction on input image.
            
            :param uint8 img: grayscale image to be gamma corrected.
            :param float correction: gamma value.
               
            :rtype: uint8 img - two dimensional uint8 numpy array corresponding to gamma corrected image. 
    """
    img = img/255.0
    img = cv2.pow(img, correction)
    return np.uint8(img*255)
Exemplo n.º 20
0
def log_chroma(img): 
    """Log-chromacity"""
    b,g,r = cv2.split(img)
    b = np.float32(b)
    g = np.float32(g)
    r = np.float32(r)
    sum = cv2.pow(b+g+r+0.1, 1/3.0)
    b = b/sum
    g = g/sum
    r = r/sum
    b = cv2.log(b)
    g = cv2.log(g)
    r = cv2.log(r)
    b = cv2.normalize(b,0,255,cv2.NORM_MINMAX)*255
    g = cv2.normalize(g,0,255,cv2.NORM_MINMAX)*255 
    r = cv2.normalize(r,0,255,cv2.NORM_MINMAX)*255 
    out = cv2.merge((np.uint8(b),np.uint8(g),np.uint8(r)))
    return out
Exemplo n.º 21
0
    def levels(self, minv, maxv, gamma=1.0, img=None):
        if img is None:
            img = self._img

        interval = maxv - minv

        _ = None
        if maxv < 255:
            _,img = cv2.threshold(img, maxv, 255, cv2.THRESH_TRUNC)
        if minv > 0:
            _,img = cv2.threshold(img, minv, 255, cv2.THRESH_TOZERO)
        if _ is not None:
            cv2.normalize(img, img, 0, 255, cv2.NORM_MINMAX)
        if gamma != 1.0:
            lut = np.array([i / 255.0 for i in range(256)])
            igamma = 1.0 / gamma
            lut = cv2.pow(lut, igamma) * 255.0
            abs64f = np.absolute(cv2.LUT(img, lut))
            img = np.uint8(abs64f)
        return _, img
Exemplo n.º 22
0
    def test_cudaarithm_arithmetic(self):
        npMat1 = np.random.random((128, 128, 3)) - 0.5
        npMat2 = np.random.random((128, 128, 3)) - 0.5

        cuMat1 = cv.cuda_GpuMat()
        cuMat2 = cv.cuda_GpuMat()
        cuMat1.upload(npMat1)
        cuMat2.upload(npMat2)

        self.assertTrue(np.allclose(cv.cuda.add(cuMat1, cuMat2).download(),
                                         cv.add(npMat1, npMat2)))

        self.assertTrue(np.allclose(cv.cuda.subtract(cuMat1, cuMat2).download(),
                                         cv.subtract(npMat1, npMat2)))

        self.assertTrue(np.allclose(cv.cuda.multiply(cuMat1, cuMat2).download(),
                                         cv.multiply(npMat1, npMat2)))

        self.assertTrue(np.allclose(cv.cuda.divide(cuMat1, cuMat2).download(),
                                         cv.divide(npMat1, npMat2)))

        self.assertTrue(np.allclose(cv.cuda.absdiff(cuMat1, cuMat2).download(),
                                         cv.absdiff(npMat1, npMat2)))

        self.assertTrue(np.allclose(cv.cuda.compare(cuMat1, cuMat2, cv.CMP_GE).download(),
                                         cv.compare(npMat1, npMat2, cv.CMP_GE)))

        self.assertTrue(np.allclose(cv.cuda.abs(cuMat1).download(),
                                         np.abs(npMat1)))

        self.assertTrue(np.allclose(cv.cuda.sqrt(cv.cuda.sqr(cuMat1)).download(),
                                    cv.cuda.abs(cuMat1).download()))


        self.assertTrue(np.allclose(cv.cuda.log(cv.cuda.exp(cuMat1)).download(),
                                                            npMat1))

        self.assertTrue(np.allclose(cv.cuda.pow(cuMat1, 2).download(),
                                         cv.pow(npMat1, 2)))
Exemplo n.º 23
0
def gamma_correction():
	cv2.destroyAllWindows()
	global pannelGammaCorrection, path, updated_path, gammaValue
	gamma = float(gammaValue.get())
	img = cv2.imread(updated_path,0)

	pathGammaCorr = 'Gamma Corrected.jpg'
	updated_path = pathGammaCorr

	img = image_resize(img)
	img = img/255.0
	img = cv2.pow(img, (1.0/gamma))
	
	# Write the image
	cv2.imwrite(pathGammaCorr, img*255)

	new = cv2.imread(pathGammaCorr)
	new = Image.fromarray(new)
	new = ImageTk.PhotoImage(new)

	pannelGammaCorrection = Label(image=new)
	pannelGammaCorrection.image = new
	pannelGammaCorrection.grid(row=0, column=2, columnspan=2, rowspan=24, sticky=W+E+N+S, padx=150, pady=10)
Exemplo n.º 24
0
def RMSD(questionID, target, master):
    # Get width, height, and number of channels of the master image
    master_height, master_width = master.shape[:2]
    master_channel = len(master.shape)

    # Get width, height, and number of channels of the target image
    target_height, target_width = target.shape[:2]
    target_channel = len(target.shape)

    # Validate the height, width and channels of the input image
    if (master_height != target_height or master_width != target_width or
            master_channel != target_channel):
        return -1
    else:
        nonZero_target = cv2.countNonZero(target)
        nonZero_master = cv2.countNonZero(master)

        if (questionID == 1):
            if (nonZero_target < 1200000):
                return -1
        elif (questionID == 2):
            if (nonZero_target < 700000):
                return -1
        else:
            return -1

        total_diff = 0.0
        master_channels = cv2.split(master)
        target_channels = cv2.split(target)

        for i in range(0, len(master_channels), 1):
            dst = cv2.absdiff(master_channels[i], target_channels[i])
            dst = cv2.pow(dst, 2)
            mean = cv2.mean(dst)
            total_diff = total_diff + mean[0]**(1 / 2.0)

        return total_diff
Exemplo n.º 25
0
def RMSD(target, master):
    # Note: use grayscale images only

    # Get width, height, and number of channels of the master image
    master_height, master_width = master.shape[:2]
    master_channel = len(master.shape)

    # Get width, height, and number of channels of the target image
    target_height, target_width = target.shape[:2]
    target_channel = len(target.shape)

    # Validate the height, width and channels of the input image
    if (master_height != target_height or master_width != target_width or
            master_channel != target_channel):
        return -1
    else:

        total_diff = 0.0
        dst = cv2.absdiff(master, target)
        dst = cv2.pow(dst, 2)
        mean = cv2.mean(dst)
        total_diff = mean[0]**(1 / 2.0)

        return total_diff
Exemplo n.º 26
0
def random_manipulation(img, manipulation=None):

    if manipulation == None:
        manipulation = np.random.choice(MANIPULATIONS)

    if manipulation.startswith('jpg'):
        quality = int(manipulation[3:])
        out = BytesIO()
        im = Image.fromarray(img)
        im.save(out, format='jpeg', quality=quality)
        im_decoded = jpeg.JPEG(np.frombuffer(out.getvalue(), dtype=np.uint8)).decode()
        del out
        del im
    elif manipulation.startswith('gamma'):
        gamma = float(manipulation[5:])
        # alternatively use skimage.exposure.adjust_gamma
        # img = skimage.exposure.adjust_gamma(img, gamma)
        im_decoded = np.uint8(cv2.pow(img / 255., gamma)*255.)
    elif manipulation.startswith('bicubic'):
        scale = float(manipulation[7:])
        im_decoded = cv2.resize(img,(0,0), fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC)
    else:
        return img
    return im_decoded
Exemplo n.º 27
0
def gamma_correction(img, correction):
    img = img/255.0
    img = cv2.pow(img, correction)
    return np.uint8(img*255)
Exemplo n.º 28
0
print("loading")

import cv2
import numpy as np

img_orig = cv2.imread("Lenna.png")
img_orig = np.double(img_orig) / 255.0

mul = float(raw_input("multiplier (default 1.0) :") or 1.0)
gamma = float(raw_input("gamma (default 1.0):") or 1.0)

img_res = cv2.pow(img_orig, gamma)
img_res = cv2.scaleAdd(img_res, mul - 1.0, img_res)

cv2.imshow("original", img_orig)
cv2.moveWindow("original", 0, 0)
cv2.imshow("result", img_res)
cv2.moveWindow("result", 512, 0)

#cv2.imshow("original, result", np.hstack( (img_orig, img_res) ))
#cv2.moveWindow("original, result", 0, 0)

cv2.waitKey(0)
cv2.destroyAllWindows()
Exemplo n.º 29
0
def correct_gamma(img, correction):

    temp = img.copy()/255.0
    temp = np.array(temp, dtype=np.float32)
    temp = cv2.pow(temp, 1./correction)*255.0
    return temp
Exemplo n.º 30
0
def view_superwhite(img):
    threshold = 512/1023 
    img = img * (img > threshold)

    return img

if __name__ == '__main__':

    # tiffのデータをread
    img = cv2.imread(File_name, cv2.IMREAD_ANYCOLOR|cv2.IMREAD_ANYDEPTH)

    # 0..1 の範囲に正規化
    normalized_val = 2**(4 * img.dtype.num) - 1
    img             = img/normalized_val

    img = cv2.pow(img, 3.5)
    img = img * normalized_val
    img = np.uint8(img)
    img = img/normalized_val
    img = cv2.pow(img, 1/3.5)

    # 画像のプレビュー
    cv2.imshow('bbb.tif', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # 出力用に 0..1 → 0..65535 の変換を実施
    out_img = img * normalized_val_uint8
    out_img = np.uint8(out_img)

    # 保存