def map_quad_to_quad(img, map, imgX, imgY, mapX, mapY): u1=mapX[0]; u2=mapX[1]; u3=mapX[2]; u4=mapX[3] v1=mapY[0]; v2=mapY[1]; v3=mapY[2]; v4=mapY[3] x1=imgX[0]; x2=imgX[1]; x3=imgX[2]; x4=imgX[3] y1=imgY[0]; y2=imgY[1]; y3=imgY[3]; y4=imgY[3] try: bigMat = np.linalg.inv(np.asmatrix([[ u1, u2, u3, u4, 0, 0, 0, 0 ], [ v1, v2, v3, v4, 0, 0, 0, 0 ], [ 1, 1, 1, 1, 0, 0, 0, 0 ], [ 0, 0, 0, 0, u1, u2, u3, u4 ], [ 0, 0, 0, 0, v1, v2, v3, v4 ], [ 0, 0, 0, 0, 1, 1, 1, 1 ], [-x1*u1,-u2*x2,-u3*x3,-u4*x4,-u1*y1,-u2*y2,-u3*y3,-u4*y4], [-x1*v1,-v2*x2,-v3*x3,-v4*x4,-v1*y1,-v2*y2,-v3*y3,-v4*y4] ])) cordinatesVector = np.asmatrix((np.hstack((mapX,mapY)))) shifted = cordinatesVector * bigMat shifted = np.hstack((shifted,np.ones((1,1)))) # shifted = np.transpose(np.hstack((shifted,[1]))) shifted = np.reshape(shifted,(3,3)) maps = shifted * np.transpose(np.asmatrix([ mapX, mapY, 1] )) maps = maps / maps[2] return maps[0],maps[1] except Exception as e: ipcv.debug(e)
def filter_highpass(img, cutoffFrequency, order=1, filterShape=ipcv.IPCV_IDEAL): """ :purpose: generates a highpass filter :inputs: img [np.ndarray] '--> img to generate filter for cutoffFrequency [np.ndarray] '--> notch offset order '--> order for butterworth filter filterShape '--> type of filter to apply :return: frequency filter [np.ndarray] """ try: lowPass = ipcv.filter_lowpass(img, cutoffFrequency, order, filterShape) highPass = 1 - lowPass return highPass except Exception as e: ipcv.debug(e)
def filter_bandreject(img, radialCenter, bandwidth, order=1, filterShape=ipcv.IPCV_IDEAL): """ :purpose: generates a bandreject filter :inputs: img [np.ndarray] '--> img to generate filter for radialCenter [np.ndarray] '--> size of bandpass bandwidth [np.ndarray] '--> size of bandpass order [int] '--> order for butterworth filter filterShape [int] '--> type of filter to apply :return: frequency filter [np.ndarray] """ try: dims = ipcv.dimensions(img) r = dims["rows"] c = dims["cols"] u = np.arange(r) v = np.arange(c) u, v = np.meshgrid(u, v) D = np.sqrt((u - r / 2)**2 + (v - c / 2)**2) if filterShape == ipcv.IPCV_IDEAL: D[D < (radialCenter - bandwidth / 2)] = 1 D[D >= (radialCenter + bandwidth / 2)] = 1 D[D != 1] = 0 elif filterShape == ipcv.IPCV_GAUSSIAN: xp = -.5 * ((D**2 - radialCenter**2) / (D * bandwidth))**2 D = 1 - np.exp(xp) D = np.clip(D, 0, 1) elif filterShape == ipcv.IPCV_BUTTERWORTH: denom = 1.0 + ((D * bandwidth) / (D**2 - radialCenter**2))**(2 * order) D = 1.0 / denom return D except Exception as e: ipcv.debug(e)
def filter_notchreject(img, notchCenter, notchRadius, order=1, filterShape=ipcv.IPCV_IDEAL): """ :purpose: generates a notch reject filter :inputs: img [np.ndarray] '--> img to generate filter for notchCenter [tuple] '--> notch offset notchRadius '--> radius of the notch filterShape '--> type of filter to apply :return: frequency filter [np.ndarray] """ try: dims = ipcv.dimensions(img) r = dims["rows"] c = dims["cols"] u = np.arange(r) v = np.arange(c) u, v = np.meshgrid(u, v) uCenter = notchCenter[0] vCenter = notchCenter[1] D1 = np.sqrt( (u-r/2-uCenter)**2 + (v-c/2-vCenter)**2 ) D2 = np.sqrt( (u-r/2+uCenter)**2 + (v-c/2+vCenter)**2 ) if filterShape == ipcv.IPCV_IDEAL: H = np.zeros( (r,c) ) H[D1 <= notchRadius] = 1 H[D2 <= notchRadius] = 1 elif filterShape == ipcv.IPCV_GAUSSIAN: xp = -.5 * ( (D1 * D2)/(notchRadius**2) ) H = 1 - np.exp( xp ) elif filterShape == ipcv.IPCV_BUTTERWORTH: denom = 1 + ( (notchRadius**2) / (D1 * D2) )**order H = 1 / denom return H except Exception as e: ipcv.debug(e)
def map_rotation_scale(src, rotation=0, scale=[1, 1]): try: theta = np.radians(rotation) srcDims = ipcv.dimensions(src, returnType="dictionary") K = srcDims['cols'] L = srcDims['rows'] W = scale[0] H = scale[1] M = K * W N = L * H x = K y = H dimVector = np.asmatrix([x, y, 1]) # SCALING scaleMat = np.asarray([[W, 0, 0], [0, H, 0], [0, 0, 1]]) dimVector = dimVector * scaleMat scaledDims = np.asmatrix( [np.arange(dimVector[0, 0]), np.arange(dimVector[0, 1]), 1]) dimVector[0, 0] = dimVector[0, 0] - M / 2 dimVector[0, 1] = N / 2 - dimVector[0, 1] # ROTATION sinTheta = np.sin(theta) cosTheta = np.cos(theta) rotationMat = np.asmatrix([[cosTheta, -sinTheta, 0.0], [sinTheta, cosTheta, 0.0], [0., 0., 1.0]]) dimVector = dimVector * rotationMat #Realigning Image about corner dimVector[0, 0] = dimVector[0, 0] + K / 2 dimVector[0, 1] = L / 2 - dimVector[0, 1] return dimVector[0, 0].astype(IPCV_32F), dimVector[0, 1].astype(IPCV_32F) except Exception as e: ipcv.debug(e)
def filter_lowpass(img, cutoffFrequency, order=1, filterShape=ipcv.IPCV_IDEAL): """ :purpose: generates a lowpass filter :inputs: img [np.ndarray] '--> img to generate filter for cutoffFrequency [np.ndarray] '--> notch offset order '--> order for butterworth filter filterShape '--> type of filter to apply :return: frequency filter [np.ndarray] """ try: dims = ipcv.dimensions(img) r = dims["rows"] c = dims["cols"] u = np.arange(r) v = np.arange(c) u, v = np.meshgrid(u, v) lowPass = np.sqrt((u - r / 2)**2 + (v - c / 2)**2) if filterShape == ipcv.IPCV_IDEAL: lowPass[lowPass <= cutoffFrequency] = 1 lowPass[lowPass >= cutoffFrequency] = 0 elif filterShape == ipcv.IPCV_GAUSSIAN: xp = -1 * (lowPass**2) / (2 * cutoffFrequency**2) lowPass = np.exp(xp) lowPass = np.clip(lowPass, 0, 1) elif filterShape == ipcv.IPCV_BUTTERWORTH: denom = 1.0 + (lowPass / cutoffFrequency)**(2 * order) lowPass = 1.0 / denom return lowPass except Exception as e: ipcv.debug(e)
def frequency_filter(img, frequencyFilter, delta=0): """ :purpose: applies a frequency filter to an image :inputs: img [np.ndarray] '--> image to be filtered frequencyFilter [np.ndarray] '--> filter to apply to image delta [int] '--> offset to be added to image at the end :return: filtered image """ try: #generating deep copy img = img.copy() rows, cols, bands, _ = ipcv.dimensions(img, 't') #preparing freq and filter arrays freqFiltered = np.zeros((rows, cols, bands)).astype(ipcv.IPCV_128C) spatialFiltered = np.zeros((rows, cols, bands)).astype(ipcv.IPCV_128C) x, y = np.indices((rows, cols)) shifter = (-1)**(x + y) #making image 3D if necessary for computational ese if len(img.shape) == 2: img = img.reshape((rows, cols, 1)) for band in range(bands): #shifting image band by band spatial = (img[:, :, band] * shifter).copy() fft = np.fft.fft2(spatial) #applying frequency filter freqFiltered[:, :, band] = fft * frequencyFilter spatialFiltered[:, :, band] = np.abs( np.fft.ifft2(freqFiltered[:, :, band])) * shifter return (spatialFiltered + delta) except Exception as e: ipcv.debug(e)
def frequency_filter(img, frequencyFilter, delta=0): try: rows, cols, bands, _ = ipcv.dimensions(img, 't') freqFiltered = np.zeros((rows, cols, bands)) x, y = np.indices((rows, cols)) shifter = np.dstack( ((-1)**(x + y), ) * bands) if bands > 1 else (-1)**(x + y) src = img.copy() * shifter fft = np.fft.fft2(src) frequencyFilter = np.dstack( (frequencyFilter, ) * bands) if bands > 1 else frequencyFilter freqFiltered = fft * frequencyFilter spatialFiltered = np.abs(np.fft.ifft2(freqFiltered)) spatialFiltered = shifter * spatialFiltered return (spatialFiltered + delta).astype(ipcv.IPCV_8U) except Exception as e: ipcv.debug(e)
def fft_display(img, videoFilename=None): try: img = img.copy() dims = ipcv.dimensions(img) r, c = dims["rows"], dims["cols"] temp = np.zeros((r, c)) # generating FFT # FFT = np.fft.fftshift(np.fft.fft(img)) # FFT = np.fft.fftshift( np.fft.fft2(img) ) # logFFT = np.log( np.abs( FFT / np.sqrt(FFT.size) ) ).astype(ipcv.IPCV_8U) FFT = np.fft.fft2(img) # print("AVERAGE VALUE IS EQUAL TO:",FFT.flat[0]) FFT = np.fft.fftshift(FFT) FFT = np.abs(FFT) logFFT = np.log10(FFT) logFFT = (logFFT / np.max(logFFT)) * 255 print("MAX IS EQUAL TO:", np.max(logFFT)) print("MIN IS EQUAL TO:", np.min(logFFT)) # creating array to poulate with maximum values maximumValues = np.flipud(np.argsort(logFFT.flatten())) used = temp.copy() current = temp.copy() currentScaled = temp.copy() summed = temp.copy() #creating writer and image window cv2.namedWindow(videoFilename) writer = create_video_writer(img.shape, videoFilename) for freqIndex in maximumValues: # for index in np.arange(0,maximumValues.size,2) # puting frequency in 'used' array used.flat[freqIndex] = logFFT.flat[freqIndex] # returning the spatial sine wave for freq temp.flat[freqIndex] = logFFT.flat[freqIndex] current = np.fft.ifft2(temp) temp.flat[freqIndex] = 0 print("MAX IS EQUAL TO:", np.max(current)) print("MIN IS EQUAL TO:", np.min(current)) #scaling the current currentScaled = ( (current - np.min(current)) / np.max(current)) * 255 #summing up all the freq summed = summed + current #stiching all images together frame = stich(img, logFFT, used, current, currentScaled, summed) print("frame dataType =", frame.dtype) #writing frame if writer.isOpened(): writer.write(frame) #displaying image cv2.imshow(videoFilename, frame) action = ipcv.flush() if action == "pause": action = ipcv.flush() if action == "pause": continue elif action == "exit": writer.release() sys.exit() except Exception as e: ipcv.debug(e)
def filter2D(src, dstDepth, kernel, delta=0, maxCount=255): """ :NAME: filter2D :PURPOSE: this method applies a spatial filter to an image :CATEGORY: ipcv -- spatial filtering and modification tool :INPUTS: src [numpy.ndarray] input image dstDepth [IPCV type] the dtype of the dst array kernel [numpy.ndarray] the kernel to be applied to the image delta [int,float] offset to be added to the image maxCount [int] maximum value of the output image :RETURN VALUE: filtered image in the form of a numpy.ndarray :ERROR CHECKING: ValueError TypeError :REQUIRES: numpy :MODIFICATION HISTORY: Engineer: Jeff Maggio original: 10/12/2016 """ #ERROR CHECKING ipcv.type_check(src, np.ndarray, "src") # ipcv.type_check(dstDepth, ipcv.IPCV_TYPES,"dstDepth") ipcv.type_check(kernel, np.ndarray, "kernel") ipcv.type_check(delta, (int, float), "delta") ipcv.type_check(maxCount, (int, float), "maxCount") ipcv.value_check(maxCount, 'b', (0, ':'), "maxCount") try: #Converting to float64 (only if necessary) if src.dtype != ipcv.IPCV_64F: src = src.astype(ipcv.IPCV_64F) if kernel.dtype != ipcv.IPCV_64F: kernel = kernel.astype(ipcv.IPCV_64F) #Normalizing the kernel weight = np.sum(kernel) weight = 1.0 if weight == 0.0 else weight kernel = kernel / weight dst = np.zeros(src.shape) rowOffset = kernel.shape[0] // 2 colOffset = kernel.shape[1] // 2 src = np.roll(src, rowOffset, axis=0) src = np.roll(src, colOffset, axis=1) for element in range(kernel.size): dst = dst + (src * kernel.flat[element]) src = np.roll(src, -1, axis=(element % 2)) dst = np.clip(dst + delta, 0, maxCount) if (delta > 0.0) else np.clip( dst, 0, maxCount) return dst.astype(dstDepth) except Exception as e: ipcv.debug(e)
def quickplot(values,colors,labels=None,filename=None,display=True,save=False,\ xLimits=(0,255),verticalMarkers = None, horizontalMarkers = None,\ xLabel = None,yLabel=None): # ERROR CHECKING if isinstance(values, (tuple, np.ndarray)) == False: print( "\r\ninput 'values' must be a tuple or structured numpy array currently {0}\r\n" .format(type(values))) raise TypeError if isinstance(colors, tuple) == False: print("\r\ninput 'colors' must be a tuple currently {0}\r\n".format( type(colors))) raise TypeError if isinstance(filename, (str, type(None))) == False: print( "\r\ninput 'filename' must be string or NoneType, currently{0}\r\n" .format(type(filename))) raise TypeError if isinstance(labels, (tuple, type(None))) == False: print("\r\ninput 'labels' must be tuple or NoneType, currently{0}\r\n". format(type(labels))) raise TypeError if len(values) != len(colors): print("\r\nvalues and colors must be a tuple of the same length\r\n") raise ValueError if isinstance(verticalMarkers, (tuple, type(None))) == False: print( "\r\nverticalMarker must be of tuple or NoneType, currently{0}\r\n" .format(type(verticalMarkers))) raise TypeError if isinstance(horizontalMarkers, (tuple, type(None))) == False: print( "\r\nhorizontalMarker must be tuple or NoneType, currently{0}\r\n". format(type(horizontalMarkers))) raise TypeError if isinstance(xLabel, (type(None), str)) == False: print("\r\nxLabel must be string or NoneType, currently{0}\r\n".format( type(xLabel))) raise TypeError if isinstance(yLabel, (type(None), str)) == False: print("\r\nyLabel must be string or NoneType, currently{0}\r\n".format( type(yLabel))) raise TypeError try: #THIS IS TERRIBLE CODING AND NEEDS TO BE FIXED AT SOME POINT # if sArray == False: if isinstance(labels, type(None)): numberPlots = len(colors) labels = [] for plotNumber in range(numberPlots): name = "set {0}".format(plotNumber) labels.append(name) elif len(labels) != len(colors): print("\r\nthere must a label for every plot, or none at all\r\n") raise ValueError #iterating through the lists to return plots = [] for index in range(len(values)): color = colors[index] data = values[index] label = labels[index] axes = plt.plot(data, color=color, label=label) plots.append(axes) plt.legend(handles=plots, labels=labels) if isinstance(verticalMarkers, tuple): for verticalMarker in verticalMarkers: plt.axvline(verticalMarker) if isinstance(horizontalMarkers, tuple): for horizontalMarker in horizontalMarkers: plt.axhline(horizontalMarker) if isinstance(xLabel, str): plt.xlabel(xLabel) if isinstance(yLabel, str): plt.ylabel(yLabel) plt.xlim(xLimits) if isinstance(filename, str): plt.title(filename) if save == True: plt.savefig(filename) elif isinstance(filename, str) == False and save == True: print("\r\ncannot save figure without valid filename\r\n") raise RuntimeError if display == True: plt.show() return plt except Exception as e: ipcv.debug(e)