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
def online_variance(new_data,curr_var,curr_iter,curr_mean): if curr_iter==1: new_mean = new_data; new_var = 0; return new_mean,new_var; else: pa=cv2.subtract(new_data,curr_mean); pa=cv2.divide(pa,curr_iter,1); new_mean=cv2.add(pa,curr_mean); #new_mean = curr_mean + (new_data - curr_mean)/curr_iter; prev_S = curr_var * (curr_iter - 2); # pd1=cv2.subtract(new_data,curr_mean); pd2=cv2.subtract(new_data,new_mean); pd=cv2.multiply(pd1,pd2); new_S=cv2.add(pd,prev_S); #new_S = prev_S + (new_data - curr_mean) .* (new_data - new_mean); new_var=cv2.divide(new_S,curr_iter-1); #new_var = new_S/(curr_iter - 1); return new_mean,new_var;
def imageenhancement(image): hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV) bgImg,fundusMask = computebgimg(image) bgImg = cv2.multiply(image[:,:,1].astype(float),bgImg.astype(float)) ldrift,cdrift = LumConDrift(bgImg,fundusMask) g = image[:,:,1].astype(float) imgCorr = cv2.divide(cv2.subtract(g,ldrift),(cv2.add(cdrift,0.0001))) imgCorr = cv2.multiply(imgCorr,fundusMask.astype(float)) imgCorr = cv2.add(imgCorr,np.abs(np.min(imgCorr))) imgCorr = cv2.divide(imgCorr,np.max(imgCorr)) imgCorr = cv2.multiply(imgCorr,fundusMask.astype(float)) image = image.astype(float) image[:,:,0] = cv2.divide(cv2.multiply(imgCorr,image[:,:,0]),hsv[:,:,2].astype(float)) image[:,:,1] = cv2.divide(cv2.multiply(imgCorr,image[:,:,1]),hsv[:,:,2].astype(float)) image[:,:,2] = cv2.divide(cv2.multiply(imgCorr,image[:,:,2]),hsv[:,:,2].astype(float)) fundusMask = fundusMask.astype(float) image[:,:,0] = cv2.multiply(image[:,:,0],fundusMask) image[:,:,1] = cv2.multiply(image[:,:,1],fundusMask) image[:,:,2] = cv2.multiply(image[:,:,2],fundusMask) out = image[:,:,1]*255 return out
def Binary_Fit(Img, u, KI, KONE, Ksigma, epsilon): Hu=np.float32(0.5*(1+(2/np.pi)*np.arctan(u/epsilon))) I=cv2.multiply(Img,Hu) c1=cv2.filter2D(Hu,-1,Ksigma) c2=cv2.filter2D(I,-1,Ksigma) f1=cv2.divide(c2,c1) f2=cv2.divide(KI-c2,KONE-c1) return (f1,f2)
def compute_DELTAE(imagename1,imagename2): img1 = cv2.imread(imagename1) img2 = cv2.imread(imagename2) img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2LAB) img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2LAB) #cv2.imwrite(imagename2+".png",img1) # s1 = cv2.absdiff(img1,img2) # s1 = np.float32(s1) # s1 = cv2.multiply(s1,s1) # s1 = cv2.sqrt(s1) L1,a1,b1 = cv2.split(img1) L2,a2,b2 = cv2.split(img2) dL = L1 - L2 da = a1-a2 db = b1-b2 # cv2.imwrite(imagename2+".png",dL) # dL_2 = cv2.multiply(dL,dL) # da_2 = cv2.multiply(da,da) # db_2 = cv2.multiply(db,db) # dL_2 = np.float32(dL_2) # da_2 = np.float32(da_2) # db_2 = np.float32(db_2) # dE = cv2.sqrt( (dL_2) + (da_2) + (db_2)) # mde = cv2.mean(dE) # print mde c1 = np.sqrt(cv2.multiply(a1,a1) + cv2.multiply(b1,b1)) c2 = np.sqrt(cv2.multiply(a2,a2) + cv2.multiply(b2,b2)) dCab = c1-c2 dH = np.sqrt(cv2.multiply(da,da) + cv2.multiply(db,db)- cv2.multiply(db,db)) sL = 1 K1 = 0.045 #can be changed K2 = 0.015 #can be changed sC = 1+K1*c1 sH = 1+K2 *c1 kL = 1 #can be changed t1 = cv2.divide(dL,kL*sL) t2 = cv2.divide(dCab,sC) t3 = cv2.divide(dH,sH) t1 = cv2.multiply(t1,t1) t2 = cv2.multiply(t2,t2) t3 = cv2.multiply(t3,t3) t1 = np.float32(t1) t2 = np.float32(t2) t3 = np.float32(t3) dE = cv2.sqrt(t1+t2+t3) mde = cv2.mean(dE) return "{0:.4f}".format(mde[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)
def getNormalizedRGB(self, rgb): rgb32f=np.float32(rgb) b,g,r=cv2.split(rgb32f) sum_rgb=b+g+r b[:,:]=0 g=cv2.divide(g, sum_rgb) r=cv2.divide(r, sum_rgb) split_bgr=cv2.merge((b,g,r)) return split_bgr
def test_on_video(net, vid_fn, out_fn): # capture # cap = cv.VideoCapture(0) cap = cv.VideoCapture(vid_fn) fps = cap.get(cv.cv.CV_CAP_PROP_FPS) ret, img = cap.read() # writer orig_shape = (227, 227) # img.shape fourcc = cv.cv.CV_FOURCC(*'XVID') wri = cv.VideoWriter(out_fn, fourcc, fps, orig_shape) frame = 0 print('before read') ## print(cap) ## print(fps) ## print(vid_fn) ## print(cap.isOpened()) while(cap.isOpened()): ret, img = cap.read() img_mean, img_std = cv.meanStdDev(img) r = cv.subtract(img[:,:,0], img_mean[0]) g = cv.subtract(img[:,:,1], img_mean[1]) b = cv.subtract(img[:,:,2], img_mean[2]) r = cv.divide(r, img_std[0]) g = cv.divide(g, img_std[1]) b = cv.divide(b, img_std[2]) test_img = np.zeros(img.shape) test_img[:,:,0] = r test_img[:,:,1] = g test_img[:,:,2] = b if ret: img = draw_joints_all(img, test_img, net) img = cv.resize(img, (orig_shape[1], orig_shape[0])) wri.write(img) cv.imshow("frame", img) frame += 1 print frame if cv.waitKey(1) & 0xFF == ord('q'): break else: print 'finished' break cap.release() wri.release() cv.destroyAllWindows()
def better_delta(data, cal): cal_over_data = (256*data / (cal.astype(np.uint16) + 1)).clip(0,255) grain_extract_cal_data = (data - cal + 128).clip(0,255) dodge_cod_ge = 255 - (cv2.divide((256 * grain_extract_cal_data), cv2.subtract(255, cal_over_data) + 1)).clip(0,255) return dodge_cod_ge.astype(np.uint8)
def get_gradient_strenght(self, frame): """ calculates the gradient strength of the image in _frame """ # smooth the image to be able to find smoothed edges frame_blurred = cv2.GaussianBlur(frame.astype(np.double), (0, 0), 3) # scale frame_blurred to [0, 1] cv2.divide(frame_blurred, 256, dst=frame_blurred) # do Sobel filtering to find the frame_blurred edges grad_x = cv2.Sobel(frame_blurred, cv2.CV_64F, 1, 0, ksize=5) grad_y = cv2.Sobel(frame_blurred, cv2.CV_64F, 0, 1, ksize=5) # calculate the gradient strength gradient_mag = frame_blurred #< reuse memory np.hypot(grad_x, grad_y, out=gradient_mag) return gradient_mag
def deltafof(image, AveImage): dfof = image.astype("float32", copy=False) AveImage = AveImage.astype("float32", copy = False) dfof = cv2.divide(dfof, AveImage, dfof) dfof -= 1.0 meanCmap = np.nanmean(dfof) stdCmap = np.nanstd(dfof) return dfof, meanCmap, stdCmap
def img_adj(frame): """On-screen live adjustment of brightness and contrast.""" global brightness, contrast brightness = 1.5 contrast = -2. sat = 0. inc = 0.5 finished = False scale = 1300./frame.shape[1] frame = cv2.resize(frame,None,fx=scale,fy=scale,interpolation = cv2.INTER_CUBIC) mod_img = frame[upperPt[1]:lowerPt[1],upperPt[0]:lowerPt[0]] prime_img = frame[:] cv2.imshow('mod',mod_img) while not finished: mod_img = adjBrtCont(prime_img,brightness, contrast) drawMatchColor(mod_img,brightness,contrast) cv2.imshow('mod',mod_img) k = cv2.waitKey(0) if k == ord('w'): #wincreases contrast contrast -= 2. mod_img = cv2.add(prime_img,np.array([contrast])) elif k == ord('s'): #s decreases contrast contrast += 2. mod_img = cv2.add(prime_img,np.array([contrast])) elif k == ord('a'): #a decreases brightness brightness -= 0.05 mod_img = cv2.multiply(prime_img,np.array([brightness])) elif k == ord('d'): #d increases brightness brightness += 0.05 mod_img = cv2.divide(prime_img,np.array([brightness])) elif k == ord('q'): #q decreases saturation sat += inc mod_img = mod_img[:,:,1]+inc elif k == ord('e'): #e decreases saturation sat -= inc mod_img = mod_img[:,:,1]-inc elif k == ord('o'): #show original cv2.imshow('original',frame) #k = cv2.waitKey() elif k == ord('x'): #x exits adjustment finished = True cv2.destroyAllWindows() cv2.destroyAllWindows() return brightness, contrast
def getConstantMotionValue(shots): #shots is a tuple of images which will be differentiated val1=cv2.absdiff(shots[0],shots[1]) val2=cv2.absdiff(shots[1],shots[2]) #average these values to get overall difference avg=cv2.add(val1,val2) avg=cv2.divide(avg,2) #finally calculate and return the weighted average return avg
def rg_color(image): B = image[:,:,0] G = image[:,:,1] R = image[:,:,2] X = cv2.add(B,G) X = cv2.add(R,X) B = cv2.divide(B,X) G = cv2.divide(G,X) R = cv2.divide(R,X) B = cv2.multiply(B,255) G = cv2.multiply(G,255) R = cv2.multiply(R,255) img = cv2.merge((B,G,R)) return img
def procesarImagen(self): if self.image is not None: # self.image = cv2.GaussianBlur(self.image, (5, 5), 0) # self.image = cv2.Canny(self.image, 100, 200) gray = cv2.cvtColor(self.image, cv2.COLOR_RGB2GRAY) \ if len(self.image.shape) >= 3 else self.image blur = cv2.GaussianBlur(gray, (21, 21), 0, 0) self.image = cv2.divide(gray, blur, scale=256) self.mostrarImagen()
def sketchify(img_rgb): """Applies pencil sketch effect to an RGB image Adapted from http://www.askaswiss.com/2016/01/how-to-create-pencil-sketch-opencv-python.html :param img_rgb: RGB image to be processed :returns: Processed grayscale image """ img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) img_blur = cv2.GaussianBlur(img_gray, (21, 21), 0, 0) img_blend = cv2.divide(img_gray, img_blur, scale=256) return img_blend
def compute(self, image): if self.computed_frames == self.num_frames: divide = np.zeros(self.background.shape, np.uint8) divide[:, :] = self.num_frames self.background = cv2.divide(self.background, divide, dtype=cv2.CV_8U) self.compute_done = True else: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if self.background is None: self.background = gray else: self.background = cv2.add(self.background, gray, dtype=cv2.CV_32S) self.computed_frames += 1
def get_gradient_strenght(self, frame): """ calculates the gradient strength of the image in _frame """ # smooth the image to be able to find smoothed edges if frame is self._frame: # take advantage of possible caching frame_blurred = self.frame_blurred else: frame_blurred = cv2.GaussianBlur(frame.astype(np.double), (0, 0), self.params['gradient/blur_radius']) # scale frame_blurred to [0, 1] cv2.divide(frame_blurred, 256, dst=frame_blurred) # do Sobel filtering to find the frame_blurred edges grad_x = cv2.Sobel(frame_blurred, cv2.CV_64F, 1, 0, ksize=5) grad_y = cv2.Sobel(frame_blurred, cv2.CV_64F, 0, 1, ksize=5) # calculate the gradient strength gradient_mag = frame_blurred #< reuse memory np.hypot(grad_x, grad_y, out=gradient_mag) return gradient_mag
def get_gradient_strenght(self, frame): """ calculates the gradient strength of the image in frame This function returns its result in buffer1 """ # smooth the frame_blurred to be able to find smoothed edges blur_radius = self.params['ground/ridge_width'] frame_blurred = cv2.GaussianBlur(frame, (0, 0), blur_radius) # scale frame_blurred to [0, 1] cv2.divide(frame_blurred, 256, dst=frame_blurred) # do Sobel filtering to find the frame_blurred edges grad_x = cv2.Sobel(frame_blurred, cv2.CV_64F, 1, 0, ksize=5) grad_y = cv2.Sobel(frame_blurred, cv2.CV_64F, 0, 1, ksize=5) # restrict to edges that go from dark to white (from top to bottom) grad_y[grad_y < 0] = 0 # calculate the gradient strength gradient_mag = frame_blurred #< reuse memory np.hypot(grad_x, grad_y, out=gradient_mag) return gradient_mag
def render(self, img_rgb): """Applies pencil sketch effect to an RGB image :param img_rgb: RGB image to be processed :returns: Processed RGB image """ img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) img_blur = cv2.GaussianBlur(img_gray, (21, 21), 0, 0) img_blend = cv2.divide(img_gray, img_blur, scale=256) # if available, blend with background canvas if self.canvas is not None: img_blend = cv2.multiply(img_blend, self.canvas, scale=1./256) return cv2.cvtColor(img_blend, cv2.COLOR_GRAY2RGB)
def myAddWeighted(src1, src2): # compare the shapes of the two sources. They must be the same # if src1.shape not src2.shape: # print "The shapes of the images are not the same. Cant blend them" # return 0, src1 # break # convert the src to 64b_float src1 = np.int32(src1) src2 = np.int32(src2) dst = np.zeros(src1.shape, dtype=np.int32) # calculate the weight arrays _,thermalWeights = weightsForThermal(src1) # _,visualWeights = weightsForVisual_spatialDelta(src2,src2.shape,(3,3)) _,visualWeights = weightsForVisual(src2) # multiply each pixel with its weights cv2.multiply(src1, thermalWeights, src1) cv2.multiply(src2, visualWeights, src2) # cv2.imshow('frameBlended', src1) # cv2.waitKey(0) # cv2.imshow('frameBlended', src2) # cv2.waitKey(0) # add the two arrays cv2.add(src1,src2,dst) # divide with the sum of the weights cv2.divide(dst, cv2.add(thermalWeights,visualWeights),dst) # dst = cv2.convertScaleAbs(dst, alpha=(255.0/65536)) # how does this alpha work? return 1, dst
def render(self,frame): canvas = cv2.imread("pen.jpg", cv2.CV_8UC1) #convert frame to gray scale. img_gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #perform binary threshold. With different values of threshold, we get different mozaic patterns ret,img_thr=cv2.threshold(img_gray,70,255,cv2.THRESH_BINARY) #apply gaussian blur img_blur = cv2.GaussianBlur(img_thr, (3, 3), 0) #invert image img_invert= 255-img_blur img_blur=cv2.GaussianBlur(img_invert, ksize=(15, 15),sigmaX=0, sigmaY=0) #generate final mozaic effect final =255-cv2.divide(255-img_thr, 255-img_blur, scale=256) #render image over a canvas return cv2.multiply(final, canvas, scale=1./256)
def centerfit(m, b, w): wm2p1 = cv2.divide(w, m*m + 1, dtype=cv2.CV_32FC1) sw = np.sum(wm2p1) smmw = np.sum(m * m * wm2p1) smw = np.sum(m * wm2p1) smbw = np.sum(m * b * wm2p1) sbw = np.sum(b * wm2p1) det = smw*smw - smmw*sw if det == 0.0: return 0.0, 0.0 xc = (smbw*sw - smw*sbw)/det; yc = (smbw*smw - smmw*sbw)/det; if np.isnan(xc) or np.isnan(yc): return 0.0, 0.0 return xc, yc
def compute_SSIM(imagename1,imagename2): img1 = cv2.imread(imagename1) img2 = cv2.imread(imagename2) print imagename2,imagename1 img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY) img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY) height,widht = img1.shape img1 = np.float64(img1) img2 = np.float64(img2) window = cv2.getGaussianKernel(11,2.0,cv2.CV_64F) C1 = 6.5025 C2 = 58.5525 mu1 = cv2.filter2D(img1,cv2.CV_64F,window) mu2 = cv2.filter2D(img2,cv2.CV_64F,window) mu1_sq = cv2.multiply(mu1,mu1) mu2_sq = cv2.multiply(mu2,mu2) mu1_mu2 = cv2.multiply(mu1,mu2) img1_sq = cv2.multiply(img1,img1) img2_sq = cv2.multiply(img2,img2) img1_img2 = cv2.multiply(img1,img2) sigma1_sq = cv2.filter2D(img1_sq,cv2.CV_64F,window) sigma1_sq = cv2.subtract(sigma1_sq,mu1_sq) sigma2_sq = cv2.filter2D(img2_sq,cv2.CV_64F,window) sigma2_sq = cv2.subtract(sigma2_sq,mu2_sq) sigma12 = cv2.filter2D(img1_img2,cv2.CV_64F,window) sigma12 = cv2.subtract(sigma12,mu1_mu2) t1 = 2*mu1_mu2 + C1 t2 = 2*sigma12 + C2 t3 = cv2.multiply(t1,t2) t1 = mu1_sq + mu2_sq + C1 t2 = sigma2_sq + sigma1_sq + C2 t1 = cv2.multiply(t1,t2) ssim_map = cv2.divide(t3,t1) mssim = cv2.mean(ssim_map) return "{0:.5f}".format(mssim[0]),height,widht
def calcGST(inputIMG, w): ## [calcGST_proto] img = inputIMG.astype(np.float32) # GST components calculation (start) # J = (J11 J12; J12 J22) - GST imgDiffX = cv.Sobel(img, cv.CV_32F, 1, 0, 3) imgDiffY = cv.Sobel(img, cv.CV_32F, 0, 1, 3) imgDiffXY = cv.multiply(imgDiffX, imgDiffY) ## [calcJ_header] imgDiffXX = cv.multiply(imgDiffX, imgDiffX) imgDiffYY = cv.multiply(imgDiffY, imgDiffY) J11 = cv.boxFilter(imgDiffXX, cv.CV_32F, (w,w)) J22 = cv.boxFilter(imgDiffYY, cv.CV_32F, (w,w)) J12 = cv.boxFilter(imgDiffXY, cv.CV_32F, (w,w)) # GST components calculations (stop) # eigenvalue calculation (start) # lambda1 = J11 + J22 + sqrt((J11-J22)^2 + 4*J12^2) # lambda2 = J11 + J22 - sqrt((J11-J22)^2 + 4*J12^2) tmp1 = J11 + J22 tmp2 = J11 - J22 tmp2 = cv.multiply(tmp2, tmp2) tmp3 = cv.multiply(J12, J12) tmp4 = np.sqrt(tmp2 + 4.0 * tmp3) lambda1 = tmp1 + tmp4 # biggest eigenvalue lambda2 = tmp1 - tmp4 # smallest eigenvalue # eigenvalue calculation (stop) # Coherency calculation (start) # Coherency = (lambda1 - lambda2)/(lambda1 + lambda2)) - measure of anisotropism # Coherency is anisotropy degree (consistency of local orientation) imgCoherencyOut = cv.divide(lambda1 - lambda2, lambda1 + lambda2) # Coherency calculation (stop) # orientation angle calculation (start) # tan(2*Alpha) = 2*J12/(J22 - J11) # Alpha = 0.5 atan2(2*J12/(J22 - J11)) imgOrientationOut = cv.phase(J22 - J11, 2.0 * J12, angleInDegrees = True) imgOrientationOut = 0.5 * imgOrientationOut # orientation angle calculation (stop) return imgCoherencyOut, imgOrientationOut
def computebgimg(image): hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) fundusMask = v > 20 b,g,r = cv2.split(image) m,n = g.shape tsize = 50 indx=0 indy=0 i = tsize tmean = np.zeros((int(m/tsize),int(n/tsize)),np.float) tstd = np.zeros((int(m/tsize),int(n/tsize)),np.float) cnt = 1 while(i<m): j = tsize while(j<n): cnt = cnt +1 if (i+tsize>=m and j+tsize<n): block = g[i-tsize:m, j-tsize:j+tsize] else: if (i+tsize<m and j+tsize>=n): block = g[i-tsize:i+tsize, j-tsize:n] else: if (i+tsize>=m and j+tsize>=n): block = g[i-tsize:m, j-tsize:n] else : block = g[i-tsize:i+tsize, j-tsize:j+tsize] mean,std = cv2.meanStdDev(block) tmean[indx,indy] = mean tstd[indx,indy] = std indy = indy+1 j = j+tsize indy = 0 indx = indx+1 i = i+tsize tmean = cv2.resize(tmean,(n,m),interpolation = cv2.INTER_CUBIC) tstd = cv2.resize(tstd,(n,m),interpolation = cv2.INTER_CUBIC) bgImg = np.abs(cv2.divide(cv2.subtract(g.astype(float),tmean),tstd)) bgImg = bgImg < 1 return bgImg,fundusMask
def _remove_image_shading(self, image, pixelk=None, ksize=None): """ Improves contrast of image by removing shaing in image. Applys morphological closing on image to extract background (this removes thin elements e.g. text and lines) then divide original image to remove background shading """ if pixelk is None: pixelk = 3 if ksize is None: ksize = 17 #imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gauss = cv2.GaussianBlur(image, (pixelk, pixelk), 0) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ksize, ksize)) closed = cv2.morphologyEx(gauss, cv2.MORPH_CLOSE, kernel) divide = cv2.divide(gauss.astype("f"), closed.astype("f")) norm = divide.copy() cv2.normalize(divide, norm, 0, 255, cv2.NORM_MINMAX) return norm
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)))
def sym_center(I): I = np.array(I, dtype = np.float64) h,w = I.shape x = np.arange(0.5, w - 1) - (w - 1) / 2.0 y = np.arange(0.5, h - 1) - (h - 1) / 2.0 xm, ym = np.meshgrid(x, y) ru = I[1:, 1:] - I[:-1, :-1] rv = I[1:, :-1] - I[:-1, 1:] ru = cv2.blur(ru, (3,3)) rv = cv2.blur(rv, (3,3)) r2 = ru * ru + rv * rv rcx, rcy = centroid(r2) w = r2 / ((xm - rcx) **2 + (ym - rcy) ** 2 + 0.00001)**0.5 m = cv2.divide(ru + rv, ru - rv) m[np.where(np.isinf(m))] = 10000 b = ym - m*xm return centerfit(m, b, w)
def render(self, img_rgb): """Applies pencil sketch effect to an RGB image :param img_rgb: RGB image to be processed :returns: Processed RGB image """ path = img_rgb img_rgb = cv2.imread(img_rgb) w, h, _ = img_rgb.shape print(w, h) self.canvas = cv2.imread(self.bg, cv2.CV_8UC1) if self.canvas is not None: self.canvas = cv2.resize(self.canvas, (h, w)) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) img_blur = cv2.GaussianBlur(img_gray, (21, 21), 0, 0) img_blend = cv2.divide(img_gray, img_blur, scale=256) # if available, blend with background canvas if self.canvas is not None: img_blend = cv2.multiply(img_blend, self.canvas, scale=1. / 256) img_blend = cv2.cvtColor(img_blend, cv2.COLOR_GRAY2RGB) cv2.imwrite(path, img_blend)
def frameFilter(self,frame): """applies a user selected filter to an image Args: frame : an image being passed in Returns: the filtered image """ output = frame if self.filter == "gray": output = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) elif self.filter == "hsv": output = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) elif self.filter == "canny": #temp = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) r, g, b = cv2.split(frame) cr = cv2.Canny(r,100,200) cg = cv2.Canny(g,100,200) cb = cv2.Canny(b,100,200) output = cv2.merge((cr,cg,cb)) #output = cv2.Canny(temp,100,200) elif self.filter == "cartoon": gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 5) edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) # Cartoonization color = cv2.bilateralFilter(frame, 9, 250, 250) output = cv2.bitwise_and(color, color, mask=edges) elif self.filter == "negative": # Negate the original image output = 1 - frame elif self.filter=="laplace": #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #s = cv2.Laplacian(gray,cv2.CV_64F, ksize = 3) r, g, b = cv2.split(frame) lr = cv2.Laplacian(r,cv2.CV_64F, ksize = 3) lg = cv2.Laplacian(g,cv2.CV_64F, ksize = 3) lb = cv2.Laplacian(b,cv2.CV_64F, ksize = 3) #cv2.imshow("split laplace",cv2.convertScaleAbs(np.concatenate((lr,lg,lb),axis = 1))) #cv2.imshow("split", np.concatenate((r,g,b),axis = 1)) output = cv2.merge((lr,lg,lb)) output = cv2.convertScaleAbs(output) elif self.filter == "xyz": output = cv2.cvtColor(frame, cv2.COLOR_BGR2XYZ) elif self.filter =="hls": output = cv2.cvtColor(frame,cv2.COLOR_BGR2HLS) elif self.filter =="pencil": img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) img_blur = cv2.GaussianBlur(img_gray, (21,21), 0, 0) output = cv2.divide(img_gray, img_blur, scale=256) elif self.filter =="warm": output = warming(frame,self) elif self.filter =="cool": output = cooling(frame,self) elif self.filter == "squares": gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray,7) arr =np.array([[-1,-1,1], [-1,9,-1], [-1,-1,-1]]) #arr = arr/sum(arr) filt = cv2.filter2D(blur,-1,arr) ret,thresh = cv2.threshold(filt,160,255,cv2.THRESH_BINARY) kernel = np.ones((5,5),np.uint8) #kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) morphed = cv2.morphologyEx(thresh,cv2.MORPH_GRADIENT, kernel) contours, hierarchy = cv2.findContours(morphed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) output = cv2.drawContours(frame, contours, -1, (0, 255, 0), 2) elif self.filter == "mirror1": H,W = frame.shape[:2] # Create a virtual camera object. Here H,W correspond to height and width of the input image frame. c1 = vcam(H=H,W=W) # Create surface object plane = meshGen(H,W) # Change the Z coordinate. By default Z is set to 1 # We generate a mirror where for each 3D point, its Z coordinate is defined as Z = 10*sin(2*pi[x/w]*10) plane.Z = 10*np.sin((plane.X/plane.W)*2*np.pi*10) # Get modified 3D points of the surface pts3d = plane.getPlane() # Project the 3D points and get corresponding 2D image coordinates using our virtual camera object c1 pts2d = c1.project(pts3d) # Get mapx and mapy from the 2d projected points map_x,map_y = c1.getMaps(pts2d) # Applying remap function to input image (img) to generate the funny mirror effect output = cv2.remap(frame,map_x,map_y,interpolation=cv2.INTER_LINEAR) elif self.filter == "mirror2": H,W = frame.shape[:2] # Creating the virtual camera object c1 = vcam(H=H,W=W) # Creating the surface object plane = meshGen(H,W) # We generate a mirror where for each 3D point, its Z coordinate is defined as Z = 20*exp^((x/w)^2 / 2*0.1*sqrt(2*pi)) #plane.Z += 20*np.exp(-0.5*((plane.X*1.0/plane.W)/0.1)**2)/(0.1*np.sqrt(2*np.pi)) #plane.Z += 20*np.exp(-0.5*((plane.Y*1.0/plane.H)/0.1)**2)/(0.1*np.sqrt(2*np.pi)) #plane.Z += 20*np.sin(2*np.pi*((plane.X-plane.W/4.0)/plane.W)) + 20*np.sin(2*np.pi*((plane.Y-plane.H/4.0)/plane.H)) plane.Z -= 100*np.sqrt((plane.X*1.0/plane.W)**2+(plane.Y*1.0/plane.H)**2) pts3d = plane.getPlane() pts2d = c1.project(pts3d) map_x,map_y = c1.getMaps(pts2d) output = cv2.remap(frame,map_x,map_y,interpolation=cv2.INTER_LINEAR) elif self.filter == "distpre": gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (7, 7), 0) # perform edge detection, then perform a dilation + erosion to # close gaps in between object edges edged = cv2.Canny(gray, 50, 100) edged = cv2.dilate(edged, None, iterations=1) edged = cv2.erode(edged, None, iterations=1) cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) # sort the contours from left-to-right and initialize the # 'pixels per metric' calibration variable (cnts, _) = imutils.contours.sort_contours(cnts) for c in cnts: if cv2.contourArea(c) > 100: output = cv2.drawContours(output,c,-1, (0, 255, 0), 2) elif self.filter == "dist": ImgDistances(frame,self) output = frame #elif self.filter =="": #output = cv2.cvtColor(frame,cv2.COLOR) return output
###### Problem - Arithmetic and Geometric Operations print 'The minimum value in the mono waterfall image is: {}'.format( waterfall_mono.min()) print 'The maximum value in the mono waterfall image is: {}'.format( waterfall_mono.max()) print 'The average value in the mono waterfall image is: {:.2f}'.format( waterfall_mono.mean()) print 'The standard deviation in the mono waterfall image is: {:.2f}'.format( waterfall_mono.std()) # subtract the mean, then divide by the standard deviation, then multiply by 10 # finally add the mean back in waterfall_arithmetic = waterfall_mono.copy() waterfall_arithmetic = cv2.absdiff(waterfall_arithmetic, waterfall_arithmetic.mean()) waterfall_arithmetic = cv2.divide(waterfall_arithmetic, waterfall_arithmetic.std()) waterfall_arithmetic = cv2.multiply(waterfall_arithmetic, 10) waterfall_arithmetic = cv2.add(waterfall_arithmetic, waterfall_arithmetic.mean()) cv2.imshow('Waterfall Arithmetic', waterfall_arithmetic) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('output/waterfall_arithmetic.png', waterfall_arithmetic) # shift the waterfall_greens image 2 pixels to the left M = np.float32([[1, 0, 2], [0, 1, 0]]) # the transformation matrix for Translation rows, cols = waterfall_greens.shape[:2] waterfall_greens_shifted = cv2.warpAffine(waterfall_greens, M, (cols, rows)) waterfall_greens_sub_shifted = cv2.subtract(waterfall_greens, waterfall_greens_shifted)
import cv2 img_src = './img.jpg' img = cv2.imread(img_src) resize_img = cv2.resize(img, (800, 600), interpolation=cv2.INTER_CUBIC) #縮放圖片 gray_img = cv2.cvtColor(resize_img, cv2.COLOR_BGR2GRAY) #灰階處理 inverted_gray_img = 255 - gray_img blurred_img = cv2.GaussianBlur(inverted_gray_img, (21, 21), 0) #高斯模糊處理 inverted_blurred_img = 255 - blurred_img sketch_img = cv2.divide(gray_img, inverted_blurred_img, scale=256.0) #影象運算處理 cv2.imshow('resize_img', resize_img) #縮放後的圖 cv2.imshow('sketch_img', sketch_img) #素描圖 cv2.waitKey(0)
def _rotare_img(img): img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) h, w = img_gray.shape[0], img_gray.shape[1] line_l = max(h, w) # kernel = np.ones((5, 5), np.uint8) img_gray = cv2.GaussianBlur(img_gray, (3, 3), 0) se = cv2.getStructuringElement(cv2.MORPH_RECT, (8, 8)) bg = cv2.morphologyEx(img_gray, cv2.MORPH_DILATE, se) out_gray = cv2.divide(img_gray, bg, scale=255) # img_edges = cv2.threshold(out_gray, 0, 255, cv2.THRESH_OTSU)[1] img_edges = auto_canny(out_gray) se = cv2.getStructuringElement(cv2.MORPH_RECT, (int(line_l / 500), 1)) img_edges = cv2.morphologyEx(img_edges, cv2.MORPH_DILATE, se) img_edges = cv2.bitwise_not(img_edges) img_edges = cv2.threshold(img_edges, 160, 255, cv2.THRESH_OTSU)[1] img_edges = cv2.bitwise_not(img_edges) # img_edges=out_gray fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 15)) # img_edges = cv2.morphologyEx(img_edges, cv2.MORPH_GRADIENT, kernel) ax[0].imshow(img_edges, cmap='gray', vmin=0, vmax=255) lines = cv2.HoughLinesP(img_edges, rho=1, theta=np.pi / 180, threshold=100, minLineLength=100, maxLineGap=line_l / 50) # lines_v = cv2.HoughLinesP(img_edges, 1, np.pi / 90, 500, minLineLength=line_l / 5, maxLineGap=2) lines_t = [] angles = [] if type(lines) == type(None): return _rotare_img(ndimage.rotate(img, 90)) for [[x1, y1, x2, y2]] in lines: cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 3) angle = np.degrees(np.arctan2(y2 - y1, x2 - x1)) lines_t.append([[x1, y1, x2, y2]]) angles.append(angle) median_angle = np.median(angles) img_rotated = ndimage.rotate(img, median_angle) lines_v_t = [] # for [[x1, y1, x2, y2]] in lines_v: # angle = np.abs(np.degrees(np.arctan2(y2 - y1, x2 - x1))) # # if angle < 92 and angle > 88: # lines_v_t.append([[x1, y1, x2, y2]]) # if type(lines) == type(None): # lines = [] # if type(lines_v) == type(None): # lines_v = [] # if len(lines_v_t) > len(lines_t): # median_angle = np.median(lines_v_t) # img_rotated = ndimage.rotate(img, median_angle + 90) # else: # median_angle = np.median(lines_t) # img_rotated = ndimage.rotate(img, median_angle) # img = ndimage.rotate(img, 90) # h, w = img.shape[0],img.shape[1] # img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # img_edges = auto_canny(img_gray) # lines = cv2.HoughLinesP(img_edges, 1, np.pi / 180.0, 500, minLineLength=w/4, maxLineGap=w/10) # angles = [] # for [[x1, y1, x2, y2]] in lines_v_t: # cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 3) # for [[x1, y1, x2, y2]] in lines: # pass # angle = np.degrees(np.arctan2(y2 - y1, x2 - x1)) # angles.append(angle) ax[1].imshow(img_rotated) return img_rotated
def dodgeV2(image, mask): return cv2.divide(image, 255-mask, scale=256)
def pen_sketch(image1, image2): return cv2.divide(image1, image2, scale=250.0)
def dodge(gray, blurred): return cv2.divide(gray, blurred, scale=256)
print '2. Add scalar to image' print '3. Subtract scalar from image' print '4. Multiply scalar to image' print '5. Divide image by scalar' print '6. Resize image by 1/2' print '7. Exit' user_input = raw_input() if user_input == '1': cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() elif user_input == '7': flag = False else: print 'Enter scalar value' scalar = int(raw_input()) if user_input == '2': img_new = cv2.add(img, scalar) elif user_input == '3': img_new = cv2.subtract(img, scalar) elif user_input == '4': img_new = cv2.divide(img, scalar) elif user_input == '5': img_new = cv2.multiply(img, scalar) elif user_input == '6': img_new = cv2.resize(img, None, fx=0.5, fy=0.5) cv2.imshow('image', img_new) cv2.waitKey(0) cv2.destroyAllWindows()
blend[col, row] = 255 else: # shift image pixel value by 8 bits # divide by the inverse of the mask tmp = (image[col, row] << 8) / (255 - mask) # print('tmp={}'.format(tmp.shape)) # make sure resulting value stays within bounds if tmp.any() > 255: tmp = 255 blend[col, row] = tmp return blend def dodgeV2(image, mask): return cv2.divide(image, 255 - mask, scale=256) def burnV2(image, mask): return 255 - cv2.divide(255 - image, 255 - mask, scale=256) def rgb_to_sketch(src_image_name): print('转换中......') img_rgb = cv2.imread(src_image_name) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) # 读取图片时直接转换操作 # img_gray = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE) img_gray_inv = 255 - img_gray img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(21, 21),
NombreImagen2 = 'UC3M.jpg' # Cargamos la imagen y se comprueba que lo ha hecho ok img1 = cv2.imread(NombreImagen1) img2 = cv2.imread(NombreImagen2) if img1 is None or img2 is None: print("Error al cargar las imagenes %s and %s" % (NombreImagen1, NombreImagen2)) else: cv2.imshow("Image1", img1) cv2.imshow("Image2", img2) # dst = cv2.addWeighted(img1,1,img2,1,0) dst = cv2.add(img1, img2) cv2.imshow("ADD", dst) dst = cv2.subtract(img1,img2) cv2.imshow("SUBSTRACT",dst) dst = cv2.multiply(img1,img2,dst,1) cv2.imshow("MULTIPLY",dst) dst = cv2.divide(img1,img2) cv2.imshow("DIVIDE",dst) cv2.waitKey(0)
def REMOVE(x, y): return cv2.divide(x, 255 - y, scale=80)
def structured(img): #image_path = "/content/8.png" image_path = img IMAGE_SIZE = 1800 def set_image_dpi(file_path): im = Image.open(file_path) length_x, width_y = im.size factor = max(1, int(IMAGE_SIZE / length_x)) size = factor * length_x, factor * width_y # size = (1800, 1800) im_resized = im.resize(size, Image.ANTIALIAS) temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png') temp_filename = temp_file.name im_resized.save(temp_filename, dpi=(300, 300)) return temp_filename #img= cv2.imread(img) #im = Image.open(img) #show image #im.show() #noise removal and smoothening BINARY_THREHOLD = 180 def image_smoothening(img): ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) blur = cv2.GaussianBlur(th2, (1, 1), 0) ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th3 def remove_noise_and_smooth(file_name): img = cv2.imread(file_name, 0) filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 41) kernel = np.ones((1, 1), np.uint8) opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel) closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) img = image_smoothening(img) or_image = cv2.bitwise_or(img, closing) return or_image img_dpi = set_image_dpi(image_path) import cv2 import numpy as np # read the image img = cv2.imread(img_dpi) # convert to gray gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # apply morphology kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (3,3)) smooth = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel) # alternate blur in place of morphology #smooth = cv2.GaussianBlur(gray, (15,15), 0) # divide gray by morphology image division = cv2.divide(gray, smooth, scale=255) # threshold result = cv2.threshold(division, 0, 255, cv2.THRESH_OTSU )[1] # save results cv2.imwrite('img_thresh.png',result) import cv2 import numpy as np from scipy.ndimage import interpolation as inter def correct_skew(image, delta=1, limit=5): def determine_score(arr, angle): data = inter.rotate(arr, angle, reshape=False, order=0) histogram = np.sum(data, axis=1) score = np.sum((histogram[1:] - histogram[:-1]) ** 2) return histogram, score #img = cv2.imread(image, cv2.IMREAD_COLOR) gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] scores = [] angles = np.arange(-limit, limit + delta, delta) for angle in angles: histogram, score = determine_score(thresh, angle) scores.append(score) best_angle = angles[scores.index(max(scores))] (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, best_angle, 1.0) rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, \ borderMode=cv2.BORDER_REPLICATE) return best_angle, rotated img3 = cv2.imread(img_dpi) angle, rotated = correct_skew(img3) extractedInformation = pytesseract.image_to_string(rotated) #print(extractedInformation) #print(pytesseract.image_to_boxes(rotated)) return extractedInformation
def dodge(x, y): return cv2.divide(x, 255 - y, scale=256)
print(" Usage: drawing.py [image.jpg/png]") try: #Inmagen image_file = sys.argv[1] except: logo() use() exit() try: print('[*] Iniciando...') sleep(0.5) print('[+] Mostrando Imagen...') image = cv2.imread(image_file) grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) grayImageInv = 255 - grayImage grayImageInv = cv2.GaussianBlur(grayImageInv, (21, 21), 0) output = cv2.divide(grayImage, 255 - grayImageInv, scale=256.0) cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE) cv2.namedWindow("pencilsketch", cv2.WINDOW_AUTOSIZE) cv2.imshow("image", image) cv2.imshow("pencilsketch", output) cv2.waitKey(0) cv2.destroyAllWindows() print('[-] Saliendo...') except: print('[x] Error') print("[x] Verificar extencion nombre de la imagen")
#Get the image file filename = 'dogs.jpeg' #Read in the image img = cv2.imread(filename) #Convert the image to Gray Scale gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Invert the image invert_gray_image = 255 - gray_image #Blur the image by using Gaussian function blurred_img = cv2.GaussianBlur(invert_gray_image, (21, 21), 0) #Invert blurred image invertBlurredImage = 255 - blurred_img #Create pencil sketch image pencilImage = cv2.divide(gray_image, invertBlurredImage, scale=256.0) #Show the image cv2_imshow(img) cv2_imshow(pencilImage)
# 如果总图片个数不超过10,用快速的方法 for i in range(6): ##将通道按照bgr的顺序组合,否则颜色失真 b, g, r = cv.split(img[i]) img[i] = cv.merge([r, g, b]) plt.subplot(321), plt.imshow(img[0]), plt.title("origin1") plt.subplot(322), plt.imshow(img[1]), plt.title("origin2") plt.subplot(323), plt.imshow(img[2]), plt.title("add") plt.subplot(324), plt.imshow(img[3]), plt.title("substarct") plt.subplot(325), plt.imshow(img[4]), plt.title("mutilpate") plt.subplot(326), plt.imshow(img[5]), plt.title("divide") plt.show() img1 = cv.imread('../image/pic.jpg') img2 = cv.imread('../image/pic2.jpg') res1 = cv.resize(img1, (320, 320), interpolation=cv.INTER_CUBIC) res2 = cv.resize(img2, (320, 320), interpolation=cv.INTER_CUBIC) ##立方插值 imgadd = cv.addWeighted(res1, 0.5, res2, 0.5, 0.5) ##亮度 imgsubtracted = cv.subtract(res1, res2) imgmultiply = cv.multiply(res1, res2) imgdivide = cv.divide(res1, res2) imgs = [res1, res2, imgadd, imgsubtracted, imgmultiply, imgdivide] ##图片数组 matplotlib_multi_pic2(imgs) # cv.imshow("origi1",res1) # cv.imshow("origi2",res2) # cv.imshow("add",imgadd) # cv.imshow("substract",imgsubtracted) # cv.imshow("multiply",imgmultiply) # cv.imshow("divide",imgdivide) # cv.waitKey(10000)
def divide_demo(m1, m2): # 两幅图片进行除运算 dst = cv.divide(m1, m2) cv.imshow("divide_demo", dst)
def divide_demo(m1, m2): dsv = cv.divide(m1, m2) cv.imshow('divide_demo', dsv)
def divide_demo(m1, m2): '''触发使用相对少''' dst = cv.divide(m1, m2) cv.imshow("divide_demo", dst)
import cv2 img1 = cv2.imread('cropped-7680-4320-1016499.jpg') resizeimg1 = cv2.resize(img1, (1280, 720)) img2 = cv2.imread('ZeRo_TwO_AnD_FraNxx.jpg') resizeimg2 = cv2.resize(img2, (1280, 720)) dst1 = cv2.add(resizeimg1, resizeimg2) dst2 = cv2.subtract(resizeimg1, resizeimg2) dst3 = cv2.multiply(resizeimg1, resizeimg2) dst4 = cv2.divide(resizeimg1, resizeimg2) cv2.imshow('add', dst1) cv2.imshow('sub', dst2) cv2.imshow('mul', dst3) cv2.imshow('div', dst4) cv2.waitKey(0) cv2.destroyAllWindows()
subg = cv2.subtract(g, scalar) subr = cv2.subtract(r, scalar) subimg = cv2.merge((subb, subg, subr)) cv2.imshow('sub_image', subimg) cv2.waitKey(0) cv2.destroyWindow('sub_image') # multiply each pixel with a scalar and display mulb = cv2.multiply(b, scalar) mulg = cv2.multiply(g, scalar) mulr = cv2.multiply(r, scalar) mulimg = cv2.merge((mulb, mulg, mulr)) cv2.imshow('mul_image', mulimg) cv2.waitKey(0) cv2.destroyWindow('mul_image') # #Divide each pixel with a scalar and display divb = cv2.divide(b, scalar) divg = cv2.divide(g, scalar) divr = cv2.divide(r, scalar) divimg = cv2.merge((divb, divg, divr)) cv2.imshow('div_image', divimg) cv2.waitKey(0) cv2.destroyWindow('div_image') # resize the image by 0.5 resizedimg = cv2.resize(img, None, fx=0.5, fy=0.5) cv2.imshow('Resized_image', resizedimg) cv2.waitKey(0) cv2.destroyWindow('Resized_image')
def main(): our_image = Image.open("empty.png") #Main st.title("Masterclass Visão Computacional") st.markdown("My first project in **streamlit!**") st.text( "Aplicações de OpenCV com Kernel para a montagem de uma ferramenta de filtros para imagens." ) st.sidebar.title("Barra lateral") #Menu com opções de páginas opcoes_menu = ["Filtros", "Sobre"] escolha = st.sidebar.selectbox("Escolha as opções", opcoes_menu) if escolha == 'Filtros': #Imagem inicial Image_file = st.file_uploader( "Upload da foto para aplicar um filtro no menu lateral", type=['jpg', 'png', 'jpeg']) if Image_file is not None: our_image = Image.open(Image_file) st.text("Imagem Original") st.sidebar.image(our_image, width=150) #Filtros que podem ser aplicados filtros = st.sidebar.radio("Filtros", [ 'Original', 'Grayscale', 'Desenho', 'Sépia', 'Canny', 'Blur', 'Contraste', 'Brightness' ]) if filtros == 'Grayscale': converted_image = np.array(our_image.convert('RGB')) gray_image = cv2.cvtColor(converted_image, cv2.COLOR_RGB2GRAY) st.image(gray_image, width=OUTPUT_WIDTH) elif filtros == 'Desenho': converted_image = np.array(our_image.convert('RGB')) gray_image = cv2.cvtColor(converted_image, cv2.COLOR_RGB2GRAY) inv_gray_image = 255 - gray_image blur_image = cv2.GaussianBlur(inv_gray_image, (21, 21), 0, 0) sketch_image = cv2.divide(gray_image, 255 - blur_image, scale=256) st.image(sketch_image, width=OUTPUT_WIDTH) elif filtros == 'Sépia': converted_image = np.array(our_image.convert('RGB')) converted_image = cv2.cvtColor(converted_image, cv2.COLOR_RGB2BGR) kernel = np.array([[0.272, 0.534, 0.131], [0.349, 0.686, 0.168], [0.393, 0.769, 0.189]]) sepia_filter = cv2.filter2D(converted_image, -1, kernel) st.image(sepia_filter, channels="BGR", width=OUTPUT_WIDTH) elif filtros == 'Blur': b_amout = st.sidebar.slider("Kernel (n x n)", 3, 81, 9, step=2) converted_image = np.array(our_image.convert('RGB')) converted_image = cv2.cvtColor(converted_image, cv2.COLOR_RGB2BGR) blur_image = cv2.GaussianBlur(converted_image, (b_amout, b_amout), 0, 0) st.image(blur_image, channels="BGR", width=OUTPUT_WIDTH) elif filtros == 'Canny': converted_image = np.array(our_image.convert('RGB')) converted_image = cv2.cvtColor(converted_image, cv2.COLOR_RGB2BGR) blur = cv2.GaussianBlur(converted_image, (11, 11), 0) canny_image = cv2.Canny(blur, 40, 100) st.image(canny_image, width=OUTPUT_WIDTH) elif filtros == 'Contraste': c_amount = st.sidebar.slider("Contraste", 0.0, 2.0, 1.0) enhancer = ImageEnhance.Contrast(our_image) contrast_image = enhancer.enhance(c_amount) st.image(contrast_image, width=OUTPUT_WIDTH) elif filtros == 'Brightness': c_amount = st.sidebar.slider("Brightness", 0.0, 2.0, 1.0) enhancer = ImageEnhance.Brightness(our_image) brightness_image = enhancer.enhance(c_amount) st.image(brightness_image, width=OUTPUT_WIDTH) elif filtros == 'Original': st.image(our_image, width=OUTPUT_WIDTH) else: st.image(our_image, width=OUTPUT_WIDTH) elif escolha == 'Sobre': st.subheader("Este é um projeto da Masterclass do curso sigmoidal") st.markdown( "Assim como esse projeto, temos outros tipos de aplicações e projetos em python no https://github.com/egustavo20/dataset_datascience" )
import cv2 img_location = "C:\\Users\\ADmin\\Downloads\\download.jpg" img = cv2.imread(img_location) gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) inveretd_grey_image = 255 - gray_image blur_img = cv2.GaussianBlur(inveretd_grey_image, (21, 21), 0) inverted_blur_img = 255 - blur_img pencil_sketch = cv2.divide(gray_image, inverted_blur_img, scale=256.0) cv2.imshow('Original Image', img) cv2.imshow('New Image ', pencil_sketch) cv2.waitKey(0)
import cv2 import sys image = cv2.imread('2.jpg') grayimg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) grayimginv = 255 - grayimg grayimginv = cv2.GaussianBlur(grayimginv, (21, 21), 0) output = cv2.divide(grayimg, 255 - grayimginv, scale=256.0) #cv2.namedWindow("image",cv2.WINDOW_AUTOSIZE) #cv2.namedWindow("pencilsketch",cv2.WINDOW_AUTOSIZE) #cv2.imshow("image",image) cv2.imwrite("pencil.jpg", output) cv2.waitKey(0) cv2.destroyAllWindows()
import cv2 img=cv2.imread("ASH.jfif") # CONVERT TO GRAYSCALE img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # INVERT GRAYSCALE IMAGE gray_image=cv2.bitwise_not(img) # blur inverted image blurred=cv2.GaussianBlur(gray_image,(21,21),0) # invert blurred image invert_blurred=cv2.bitwise_not(blurred) # final sketch sketch_image=cv2.divide(img,invert_blurred,scale=250.0) cv2.imwrite("ash.png",sketch_image) cv2.waitKey(0) cv2.destroyAllWindows()
import cv2 as cv import numpy as np src1 = cv.imread("test_images/opencv.jpg"); src2 = cv.imread("test_images/cat.jpg"); cv.imshow("input1", src1) cv.imshow("input2", src2) h, w, ch = src1.shape print("h , w, ch", h, w, ch) add_result = np.zeros(src1.shape, src1.dtype); cv.add(src1, src2, add_result); cv.imshow("add_result", add_result); sub_result = np.zeros(src1.shape, src1.dtype); cv.subtract(src1, src2, sub_result); cv.imshow("sub_result", sub_result); mul_result = np.zeros(src1.shape, src1.dtype); cv.multiply(src1, src2, mul_result); cv.imshow("mul_result", mul_result); div_result = np.zeros(src1.shape, src1.dtype); cv.divide(src1, src2, div_result); cv.imshow("div_result", div_result); cv.waitKey(0) cv.destroyAllWindows()
def divide_demo(m1, m2): dst = cv.divide(m1, m2) cv.imshow("add mdemo", dst)
# coding=gbk import cv2 as cv import numpy as np image = cv.imread("dog1.jpg") """ 图像image各像素加50 与image大小一样的矩阵 """ M = np.ones(image.shape,dtype="uint8")*50 added = cv.add(image,M) # 将图像image与M相减 subtracted = cv.subtract(image,M) # 将图像image与M相减 multiply = cv.multiply(image,M) divide = cv.divide(image,M) cv.imshow("Original_img",image) # 展示原图 cv.imshow("Added",added) # 加运算图 cv.imshow("subtracted",subtracted) # 减运算图 cv.imshow('multiply',multiply) # 乘 cv.imshow('divide',divide) # 除 cv.waitKey(0) cv.destroyAllWindows()
def burn(image, mask): return 255 - cv2.divide(255 - image, 255 - mask, scale=256)
def divide_demo(m1, m2): dst = cv.divide(m1, m2) cv.imshow('divide_demo', dst) cv.imwrite('out/Pixel_operation_mathematical_operation/divide_demo.jpg', dst)