def capture(): capture = cv.CaptureFromCAM(0) filename = str(uuid.uuid4()) while True: img = cv.QueryFrame(capture) cv.SaveImage(filename+".jpg", img) break cv.DestroyAllWindows()
def main(args): try: node_name = "ros2opencv2_cp" ROS2OpenCV2(node_name) rospy.spin() except KeyboardInterrupt: print "Shutting down ros2opencv node." cv.DestroyAllWindows()
def main(args): print("Running the recognizer ...!") try: Recognizer() rospy.spin() except KeyboardInterrupt: print "Shutting down vision node." cv.DestroyAllWindows()
def main(args): print("hello!") try: cvBridgeDemo() rospy.spin() except KeyboardInterrupt: print "Shutting down vision node." cv.DestroyAllWindows()
def blackhat(): display(src_image,"source_image") struc=cv.CreateStructuringElementEx(5,5,3,3,cv.CV_SHAPE_RECT) dst=cv.CreateImage((src_image.width,src_image.height),8,src_image.channels) temp=cv.CreateImage((src_image.width,src_image.height),8,src_image.channels) cv.MorphologyEx(src_image,dst,temp,struc,cv2.MORPH_BLACKHAT,1) display(dst,"destination image") cv.WaitKey(0) cv.DestroyAllWindows()
def main(args): try: print( tf.transformations.euler_from_quaternion( (-0.9991509151752196, 0.006177326394527312, -0.03775980328552767, 0.01528026828871064))) obj = objectDetect() obj.root.mainloop() except KeyboardInterrupt: print "Shutting down vision node." cv.DestroyAllWindows()
def _close_windows(self, all=0): """ if all: try: cv.DestroyWindow("result") except: pass for i in range(16): try: cv.DestroyWindow("face"+str(i)) except: pass """ cv.DestroyAllWindows()
def showImage(self): while True: try: self._imgData = self._videoProxy.getImageRemote( self._imgClient) cv.SetData(self._img, self._imgData[6]) cv.ShowImage("Camera_OpenCV", self._img) except KeyboardInterrupt: break except: pass if cv.WaitKey(10) == 27: break cv.DestroyAllWindows() self._unregisterImageClient()
def main_program(usn): #capture from inbuilt camera i.e web cam cap=cv.CaptureFromCAM(0) while(True): #frame for video img=cv.QueryFrame(cap) #display the image from frame cv.ShowImage("image",img) #wait for response k=cv.WaitKey(10) #if esc is pressed the break if k==27: break #if 'c' is pressed then save the image elif k==ord('c'): time=datetime.now() cv.SaveImage("face/database/image.png",img) cv.DestroyAllWindows() os.system("python face.py") path="face/database/image.png" if os.path.exists(path): #renaming the file with the usn along with the current date stmp for making it unique newPath="face/database/"+usn+str(time.month)+str(time.day)+str(time.hour)+str(time.minute)+str(time.second)+str(time.microsecond)+".png" #path1="c:python27/face/database/"+usn+".png" cmd=os.rename(path,newPath) print "image captured, resized and renamed successfully" #cv.ShowImage("image","face/database"+usn+exp+".png") else: print "no face detected......image deleted"
def showImage(self): while True: try: self._imgData = self._videoProxy.getImageRemote( self._imgClient) cv.SetData(self._img, self._imgData[6]) mat = self._img[:] frame = np.array(mat) im_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) im_h, im_s, im_v = cv2.split(im_hsv) lower = np.array([30, 0, 0]) upper = np.array([40, 255, 255]) mask = cv2.inRange(im_hsv, lower, upper) res = cv2.bitwise_and(frame, frame, mask=mask) im_gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY) im_bw = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 0) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) im_open = cv2.morphologyEx(im_bw, cv2.MORPH_OPEN, kernel) circles = cv2.HoughCircles(im_open, cv2.cv.CV_HOUGH_GRADIENT, 1, 100, param1=100, param2=10, minRadius=20, maxRadius=40) if circles is None: cv2.imshow("came", frame) else: circles = np.uint16(np.around(circles)) for i in circles[0, :]: cv2.circle(frame, (i[0], i[1]), i[2], (255, 0, 0), 5) cv2.circle(frame, (i[0], i[1]), 2, (255, 0, 255), 10) cv2.imshow("came", frame) except KeyboardInterrupt: break except: pass if cv.WaitKey(10) == 27: break cv.DestroyAllWindows() self._unregisterImageClient()
def face(faceCascade, capture): while True: _, img = capture.read() img = cv2.resize(img, (320, 240)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(30, 30), flags=cv.CV_HAAR_SCALE_IMAGE) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("camera", img) if cv.WaitKey(10) > 0: break cv.DestroyAllWindows()
def main(args): sec = "humandetector" args = sys.argv[1:] option_dict = configparse.parse_args_to_param_dict(args, sec) rospy.init_node('HumanDetector') #READ PARAMETERS: host = option_dict.get_option(sec, 'host') port = option_dict.get_option(sec, 'port') source = option_dict.get_option(sec, 'video_source') freq = option_dict.get_option(sec, 'update_frequency') # Transform is fixed transform = [[0, 0, 0.63]] detector = HumanDetector(host, port, freq, source, transform) detector.connect() detector.run() cv.DestroyAllWindows()
def sobelGradient(self, image): '''Calculates the gradient in x and y direction using Sobel mask using default 3x3 filter''' if self.image_check(image) < 0: return -1 gsimage = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) if image.channels > 1: temp = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) cv.CvtColor(image, temp, cv.CV_BGR2GRAY) gsimage = temp else: gsimage = image #smoothing image #Creating empty images for dx,dy and temporary 16 bit dx16 and dy16 dy16 = cv.CreateImage(cv.GetSize(gsimage), cv.IPL_DEPTH_16S, 1) dx16 = cv.CreateImage(cv.GetSize(gsimage), cv.IPL_DEPTH_16S, 1) dx = cv.CreateImage(cv.GetSize(gsimage), cv.IPL_DEPTH_8U, 1) dy = cv.CreateImage(cv.GetSize(gsimage), cv.IPL_DEPTH_8U, 1) #Convolving sobel mask to get gradient of dx and dy cv.Sobel(gsimage, dy16, 0, 1, apertureSize=3) cv.Sobel(gsimage, dx16, 1, 0, apertureSize=3) cv.ConvertScaleAbs(dx16, dx) cv.ConvertScaleAbs(dy16, dy) if self.visualize: while True: cv.NamedWindow("Original") cv.ShowImage("Original", gsimage) cv.NamedWindow("Sobelx") cv.ShowImage("Sobelx", dx) cv.NamedWindow("Sobely") cv.ShowImage("Sobely", dy) c = cv.WaitKey(5) if c > 0: break cv.DestroyAllWindows() return (dx16, dy16)
def main(): """Open test color images, create display window, start the search""" #cv.NamedWindow(WNDNAME, 1) os.chdir("C:\\3d-Model\\bin\\segmentation_files") for fil in glob.glob("*.png"): img0 = cv.LoadImage(fil, cv.CV_LOAD_IMAGE_COLOR) print fil # slider deleted from C version, same here and use fixed Canny param=50 img = cv.CloneImage(img0) img1 = cv.CreateImage((img0.width, img0.height), 8, 3) #cv.ShowImage(WNDNAME, img1) # force the image processing draw_squares(img1, find_squares4(img)) image = Image.open( "C:\\3d-Model\\bin\\segmentation_files\\pic_square.jpg") image.load() crop_img(fil, image) directory = "C:\\3d-Model\\bin\\segmentation_files\\" + fil os.remove(directory) print "removed" os.remove("C:\\3d-Model\\bin\\segmentation_files\\pic.jpg") os.remove("C:\\3d-Model\\bin\\segmentation_files\\pic_blur.jpg") os.remove("C:\\3d-Model\\bin\\segmentation_files\\pic_contours.jpg") os.remove("C:\\3d-Model\\bin\\segmentation_files\\pic_resize.jpg") os.remove("C:\\3d-Model\\bin\\segmentation_files\\pic_seg.jpg") os.remove("C:\\3d-Model\\bin\\segmentation_files\\pic_square.jpg") print "DONE!!! Segmentation completed successfully" #log code contour to file for progress with open('C:\\3d-Model\\bin\\segmentation_files\\progress.txt', 'w') as myFile: myFile.write("crop") cv.DestroyAllWindows()
def __showPic(self): try: import cv2.cv as cv except: return "Need OpenCV" content = urllib2.urlopen( "http://www.renren.com/validateuser.do").read() place = content.find("http://icode.renren.com/getcode.do?t=ninki&rnd=") place2 = content.find("\"/>", place) content = content[place:place2] filedata = urllib2.urlopen(content).read() imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1) cv.SetData(imagefiledata, filedata, len(filedata)) img0 = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR) cv.ShowImage("captchas", img0) cv.WaitKey() captchas = raw_input("Please enter the captchas:") cv.DestroyAllWindows() postdata = urllib.urlencode({"id": self.__id, "icode": captchas}) req = urllib2.Request(url="http://www.renren.com/validateuser.do", data=postdata) content = urllib2.urlopen(req).read()
def main(args): rospy.init_node('HumanDetector') # Get transform between base_link and camera_bottom listener = tf.TransformListener() try: listener.waitForTransform("/base_link", "/camera3_link", rospy.Time.now(), rospy.Duration(4.0)) except: pass transform = None while not rospy.is_shutdown(): print "Trying" try: now = rospy.Time.now() try: listener.waitForTransform("/base_link", "/camera3_link", now, rospy.Duration(4.0)) except: continue transform = listener.lookupTransform("/base_link", "/camera3_link", now) break except: pass if transform == None: ROS_INFO("Could not find transform between base_link and camera3_link") return print "Starting human detector" detector = HumanDetector(transform) try: rospy.spin() except KeyboardInterrupt: print "Shutting down" cv.DestroyAllWindows()
def main(): capture = cv2.VideoCapture(0) # Parametros do tamannho da imagem de captura width = 640 height = 480 # Definir um tamanho para os frames (descartando o PyramidDown if capture.isOpened(): capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width) capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height) while True: ret, entrada = capture.read() imgHSV = cv2.cvtColor(entrada, cv2.cv.CV_BGR2HSV) imgThresh = cv2.inRange(imgHSV, rangeMin, rangeMax) imgErode = cv2.erode(imgThresh, None, iterations=3) moments = cv2.moments(imgErode, True) if moments['m00'] >= minArea: x = moments['m10'] / moments['m00'] y = moments['m01'] / moments['m00'] #print(x, ", ", y) #sets size of cirlce.. can use this to determine stuff. cv2.circle(entrada, (int(x), int(y)), 50, (0, 255, 0), -1) #lines_sum = x #print("x: ", x, "y: ", y) print(x, y) sys.stdout.flush() cv2.imshow("Entrada", entrada) cv2.imshow("HSV", imgHSV) cv2.imshow("Thre", imgThresh) cv2.imshow("Erosao", imgErode) if cv.WaitKey(10) == 27: break cv.DestroyAllWindows()
class camera2(multiprocessing.Process): capture = cv.CaptureFromCAM(0) # 画像サイズの指定 cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 680) # cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_WIDTH,1200) # cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_HEIGHT,480) # a = 0 # i = 0 # while True: # if a == 0: # img = cv.QueryFrame(capture) # cv.ShowImage("camera", img) # if cv.WaitKey(10) > 0: # sbreak while True: img = cv.QueryFrame(capture) cv.ShowImage("camera", img) if cv.WaitKey(10) > 0: sbreak cv.DestroyAllWindows()
def gaussian(src, dst): cv.Smooth(src, dst, cv.CV_GAUSSIAN, 9, 9) display(src, "Source Image") display(dst, "Gaussian Smooth") cv.WaitKey(0) cv.DestroyAllWindows()
def simpleblur(src, dst): cv.Smooth(src, dst, cv.CV_BLUR, 9, 9) display(src, "Source Image") display(dst, "Simple Smooth") cv.WaitKey(0) cv.DestroyAllWindows()
def cannyTangent(self, image, smooth=True, T1=20, T2=250, eq=False, method="cv", method2="fast"): '''Gets the thresholded edge from opencv canny, and use the locations to take out the magnitude and gradient from manually calculated gradient using sobel mask''' gsimage = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) smoothed = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) final = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) if image.channels > 1: temp = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) cv.CvtColor(image, temp, cv.CV_BGR2GRAY) else: temp = image if eq: cv.EqualizeHist(temp, gsimage) else: cv.Copy(temp, gsimage) if smooth: cv.Smooth(gsimage, smoothed) final = smoothed else: cv.Copy(gsimage, final) tempo = self.visualize self.visualize = False #a = time.time() gradient = self.cannyGradient(final, t1=T1, t2=T2) #print "single canny time:", time.time() - a #a = time.time() (dx, dy) = self.sobelGradient(final) #print "single sobel time:", time.time() - a #a = time.time() tangent = self.tangent(dx, dy, gradient, method=method) #print "single tangent time:", time.time() - a #a = time.time() magnitude = self.Magnitude(dx, dy, gradient, method=method2) #print "single magnitude time:", time.time() - a self.visualize = tempo if self.visualize: jinjer = 0 while True: tan = cv.CreateImage(cv.GetSize(tangent), cv.IPL_DEPTH_8U, 1) timp = cv.CreateImage(cv.GetSize(tangent), cv.IPL_DEPTH_8U, 1) cv.Convert(tangent, tan) cv.EqualizeHist(tan, timp) cv.NamedWindow("Original") cv.MoveWindow("Original", 0, 0) cv.ShowImage("Original", final) #cv.NamedWindow("TangentCanny") #cv.ShowImage("TangentCanny", timp) cv.NamedWindow("magnitude") cv.MoveWindow("magnitude", 640, 0) cv.ShowImage("magnitude", magnitude) c = cv.WaitKey(5) jinjer += 1 if c > 0 or jinjer > 1000000: break cv.DestroyAllWindows() return (tangent, magnitude)
def __del__(self): if self._OCVM0 is not "": self._OCVM0.cancel_img_client(self._videoProxy) if self._OCVM1 is not "": self._OCVM1.cancel_img_client(self._videoProxy) cv.DestroyAllWindows()
def Bilateral(src, dst): cv.Smooth(src, dst, cv.CV_BILATERAL, 9, 9) display(src, "Source Image") display(dst, "Bilateral Smooth") cv.WaitKey(0) cv.DestroyAllWindows()
def stop(self): cv.DestroyAllWindows()
def snapL(self, L): for i,img in enumerate(L): cv.NamedWindow("snap-%d" % i, 1) cv.ShowImage("snap-%d" % i, img) cv.WaitKey() cv.DestroyAllWindows()
def main(args): try: a2r = AVI2ROS() except KeyboardInterrupt: print "Shutting down avi2ros..." cv.DestroyAllWindows()
def findCrescent(self): """ Detects a crescent within a pupil region. Uses opencv libarary methods to detect a crescent. Then initializes crescent to the area of the region found. Returns false if any errors are encountered Args: None Return: bool - True if there were no issues. False for any error """ if DEBUG: print "self.pupilPhoto is of type: " + str(type(self.pupilPhoto)) # Currently self.pupilPhoto is stored as a cvmat so we need to convert to a # numpy array before working with it. #im = np.asarray(self.pupilPhoto) # read the im from disc using absolute path im = cv2.imread( os.path.join(os.path.dirname(__file__), 'PUPILPHOTO.jpg')) if DEBUG: print "im is of type: " + str(type(im)) imblur = cv2.blur(im, (3, 3)) imgray = cv2.cvtColor(imblur, cv2.COLOR_BGR2GRAY) # TODO Take away magic (ex: 127,255,0) numbers here and make pretty # Variables at the top ret, thresh = cv2.threshold(imgray, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if DEBUG: print "Contours is of type: " + str(type(contours)) print "Contours is of id: " + str(hex(id(contours))) print "Countours: " + str(contours) cv.ShowImage("Thresholded", cv.fromarray(thresh)) cv.WaitKey(0) cv.DestroyWindow("Thresholded") cnt = contours[0] len(cnt) cv2.drawContours(im, contours, -1, (0, 255, 0), -1) cv.ShowImage("Coutours", cv.fromarray(im)) cv.WaitKey(0) cv.DestroyWindow("Contours") max_area = 0 for cnt in contours: area = cv2.contourArea(cnt) if area > max_area: max_area = area best_cnt = cnt #set the max_area found into the actual structure self.setCrescent(max_area) #show it, or exit on waitkey #cv2.imshow('imblur',imblur) if DEBUG: #find centroids of best_cnt M = cv2.moments(best_cnt) cx, cy = int(M['m10'] / M['m00']), int(M['m01'] / M['m00']) cv2.circle(imblur, (cx, cy), 5, 255, -1) cv2.imshow('thresh', thresh) if cv2.waitKey(33) == 27: cv.DestroyAllWindows() cnt = contours[0] len(cnt) cv2.drawContours(imblur, contours, -1, (0, 255, 0), -1) cv2.circle(imblur, (cx, cy), 5, 255, -1) cv.ShowImage("Contour Shading", cv.fromarray(imblur)) #cv.WaitKey(0) #cv.DestroyWindow("Testing") cv.WaitKey(0) cv.DestroyAllWindows()
def divide(self, image, column=8, row=8, option="normal", overlap=0): #Checks whether inputs are correct if self.image_check(image) < 0: return -1 if self.mn_check(column, row) < 0: return -2 if option == "normal": #sizeTuple is a tuple as follow: (width, height) sizeTuple = cv.GetSize(image) widthSlice = math.floor(sizeTuple[0] / column) heightSlice = math.floor(sizeTuple[1] / row) widthReminder = sizeTuple[0] % column heightReminder = sizeTuple[1] % column List = [] rowIndex = 0 columnIndex = 0 #In these two while loops we make every sub image, crop it from original image and add it to a list #if there are reminders, the width and height of the final row/columns will differ while columnIndex < sizeTuple[0]: if columnIndex == sizeTuple[0] - widthSlice - widthReminder: width = widthSlice + widthReminder else: width = widthSlice while rowIndex < sizeTuple[1]: if rowIndex == sizeTuple[1] - heightSlice - heightReminder: height = heightSlice + heightReminder else: height = heightSlice if columnIndex - overlap <= 0: #Overlapping the rectangles. column = columnIndex else: column = columnIndex - overlap if rowIndex - overlap <= 0: row = rowIndex else: row = rowIndex - overlap subRect = (column, row, width, height) List.append(self.crop(image, subRect)) rowIndex += height rowIndex = 0 columnIndex += width if (self.visualize): windows = range(len(List)) for x in windows: cv.NamedWindow(str(x)) while True: for x in windows: cv.ShowImage(str(x), List[x]) c = cv.WaitKey(5) if c > 0: print c break cv.DestroyAllWindows() return List else: #sizeTuple is a tuple as follow: (width, height) columnstep = 1 rowstep = 1 maxcolumn = column maxrow = row List = [] while columnstep <= maxcolumn and rowstep <= maxrow: column = columnstep row = rowstep sizeTuple = cv.GetSize(image) widthSlice = math.floor(sizeTuple[0] / column) heightSlice = math.floor(sizeTuple[1] / row) widthReminder = sizeTuple[0] % column heightReminder = sizeTuple[1] % column rowIndex = 0 columnIndex = 0 #In these two while loops we make every sub image, crop it from original image and add it to a list #if there are reminders, the width and height of the final row/columns will differ while columnIndex < sizeTuple[0]: if columnIndex == sizeTuple[0] - widthSlice - widthReminder: width = widthSlice + widthReminder else: width = widthSlice while rowIndex < sizeTuple[1]: if rowIndex == sizeTuple[ 1] - heightSlice - heightReminder: height = heightSlice + heightReminder else: height = heightSlice if columnIndex - overlap <= 0: #Overlapping the rectangles. column = columnIndex else: column = columnIndex - overlap if rowIndex - overlap <= 0: row = rowIndex else: row = rowIndex - overlap subRect = (int(column), int(row), int(width), int(height)) List.append(self.crop(image, subRect)) rowIndex += height rowIndex = 0 columnIndex += width if (self.visualize): windows = range(len(List)) for x in windows: cv.NamedWindow(str(x)) while True: for x in windows: tan = cv.CreateImage(cv.GetSize(List[x]), cv.IPL_DEPTH_8U, 1) final = cv.CreateImage(cv.GetSize(List[x]), cv.IPL_DEPTH_8U, 1) cv.CvtColor(List[x], tan, cv.CV_RGB2GRAY) cv.EqualizeHist(tan, final) cv.NamedWindow(str(x)) cv.ShowImage(str(x), final) c = cv.WaitKey(5) if c > 0: print c break cv.DestroyAllWindows() columnstep *= 2 rowstep *= 2 return List
best_r = r best_template = template_copy.copy() self.last_scale = self.scales.index(s) best_result = result.copy() # Transform back to original image sizes best_x *= int(pow(2.0, self.n_pyr)) best_y *= int(pow(2.0, self.n_pyr)) h,w = self.template.shape[:2] h = int(h * best_s) w = int(w * best_s) best_result = cv2.resize(best_result, (int(pow(2.0, self.n_pyr)) * best_result.shape[1], int(pow(2.0, self.n_pyr)) * best_result.shape[0])) display_result = np.abs(best_result)**3 cv2.imshow("Result", display_result) best_template = cv2.resize(best_template, (int(pow(2.0, self.n_pyr)) * best_template.shape[1], int(pow(2.0, self.n_pyr)) * best_template.shape[0])) cv2.imshow("Best Template", best_template) #match_box = ((best_x + w/2, best_y + h/2), (w, h), -best_r) return (best_x, best_y, w, h) if __name__ == '__main__': try: node_name = "template_tracker" TemplateTracker(node_name) rospy.spin() except KeyboardInterrupt: print "Shutting down fast match template node." cv.DestroyAllWindows()
def tangent(self, dx, dy, Mask=None, method="cv"): '''This function calculates the gradient orientation of each pixel that is in Mask''' tangent = cv.CreateImage(cv.GetSize(dx), cv.IPL_DEPTH_8U, 1) divSize = cv.GetSize(dx) tangent16U = cv.CreateImage(divSize, cv.IPL_DEPTH_32F, 1) cv.SetZero(tangent16U) if method == "slow": for x in range(divSize[0]): for y in range(divSize[1]): if Mask == None: tang = math.atan2(dy[y, x], dx[y, x]) * self.constant tangent16U[y, x] = int(tang) elif Mask[y, x] > 0: tang = math.atan2(dy[y, x], dx[y, x]) * self.constant tangent16U[y, x] = int(tang) elif Mask[y, x] == 0: tangent16U[y, x] = 0 elif method == "cv": #Calculated the arctan2 which give -pi to pi range #I create numpy arrays then reshape them in to 1 Dimesnion. #Next, I calculated arctan2 and change the range to 0-2pi and make it in degrees #I reshape back to picture format and return the picture #Numpy formatting (width, height) = cv.GetSize(dx) matdx = cv.CreateMat(height, width, cv.CV_16SC1) matdy = cv.CreateMat(height, width, cv.CV_16SC1) cv.SetZero(matdx) cv.SetZero(matdy) cv.Copy(dx, matdx, Mask) cv.Copy(dy, matdy, Mask) a = numpy.asarray(matdx) b = numpy.asarray(matdy) #Reshaping to one dimension ar = numpy.reshape(a, a.size) br = numpy.reshape(b, b.size) #Calculating Arc Tangent with quadrant information c = numpy.arctan2(br, ar) #Turning it to -180 to 180 range z = numpy.multiply(c, self.constant) result = z.astype(numpy.int32) result[result < 0] += 360 tang = numpy.reshape(result, (height, width)) tang = tang.astype(numpy.float32) mat = cv.fromarray(tang) cv.Copy(mat, tangent16U) else: dxTemp = cv.CreateImage(cv.GetSize(dx), cv.IPL_DEPTH_16S, 1) dyTemp = cv.CreateImage(cv.GetSize(dx), cv.IPL_DEPTH_16S, 1) zero = cv.CreateImage(cv.GetSize(dx), cv.IPL_DEPTH_16S, 1) cv.Add(zero, dx, dxTemp, Mask) cv.Add(zero, dy, dyTemp, Mask) dx = dxTemp dy = dyTemp for x in range(divSize[0]): for y in range(divSize[1]): if Mask[y, x] == 0: tangent16U[y, x] = 0 continue tang = math.atan2(dy[y, x], dx[y, x]) * self.constant tangent16U[y, x] = int(tang) if self.visualize: #tangent2 = cv.CreateImage(cv.GetSize(dy), cv.CV_16SC1, 1) cv.ConvertScaleAbs(tangent16U, tangent) cv.EqualizeHist(tangent, tangent) while True: cv.NamedWindow("Tangent") cv.ShowImage("Tangent", tangent) c = cv.WaitKey(5) if c > 0: break cv.DestroyAllWindows() return tangent16U