How to access the previous/next element in a for loop?

Expressed as a generator function: def neighborhood(iterable): iterator = iter(iterable) prev_item = None current_item = next(iterator) # throws StopIteration if empty. for next_item in iterator: yield (prev_item, current_item, next_item) prev_item = current_item current_item = next_item yield (prev_item, current_item, None) Usage: for prev,item,next in neighborhood(l): print prev, item, next

Duplicate log output when using Python logging module

The logging.getLogger() is returns the same instance for a given name. (Documentation) The problem is that every time you call myLogger(), it’s adding another handler to the instance, which causes the duplicate logs. Perhaps something like this? import os import time import datetime import logging loggers = {} def myLogger(name): global loggers if loggers.get(name): return … Read more

Which tkinter modules were renamed in Python 3?

The Tkinter package from Python 2 has been renamed to tkinter in Python 3, as well as other modules related to it. Here is a list of renamed modules: Tkinter → tkinter tkMessageBox → tkinter.messagebox tkColorChooser → tkinter.colorchooser tkFileDialog → tkinter.filedialog tkCommonDialog → tkinter.commondialog tkSimpleDialog → tkinter.simpledialog tkFont → tkinter.font Tkdnd → tkinter.dnd ScrolledText → … Read more

How to use OpenCV’s connectedComponentsWithStats in Python?

The function works as follows: # Import the cv2 library import cv2 # Read the image you want connected components of src = cv2.imread(‘/directorypath/image.bmp’) # Threshold it so it becomes binary ret, thresh = cv2.threshold(src,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # You need to choose 4 or 8 for connectivity type connectivity = 4 # Perform the operation output = … Read more