Code
import os, time, copy, shutil, QueueCode
import Image, ImageFilter, ImageEnhance, ImageDraw, ImageOpsCode
Code
class capture:Code
gauge_box = None # bounding box of the gauge panelCode
dial_centers = None # Dictionary keyed by dial unit, of dial center coordinatesCode
dial_radius = None # Radius in pixels of a dialCode
Code
dev = None # '/dev/video0'Code
tmpfile = None # temporary location for captured jpegCode
Code
debug = None # print a bit more informationCode
debug_nocap = None # If true, no new images will be acquiredCode
debug_logcappath = None # write all captured images to this pathCode
Code
full = None # full imageCode
dials = None # image of all dialsCode
Code
# current readingCode
cur_time = None # unix time of most recent readingCode
dial_values = None # current gauge valuesCode
dial_angles = None # current gauge anglesCode
reading = None # The final value, as one floatCode
Code
# a past reading, with difference great enough to avoid bouncingCode
prev_values = NoneCode
rot_count_adj = None # rotation counts, adjusted to assureCode
# non-decreasing valuesCode
rot_count = None # rotation counts, never calibrated. for rateCode
cumm_time = None # last cumulative resetCode
cumm_count = None # cumulative rotation countCode
Code
Code
def reset_cumm_count(self):Code
self.cumm_time = self.cur_timeCode
self.cumm_count = {0.5: 0, 2: 0}Code
Code
def get_cumm_count(self):Code
cnt_tmp = copy.copy(self.cumm_count)Code
self.reset_cumm_count()Code
return cnt_tmpCode
Code
def __init__(self, gauge_box, dial_centers, dial_radius,Code
dev='/dev/video0',Code
tempfile='temp.jpeg',Code
debug = False, debug_nocap = False,Code
debug_logcappath = None):Code
self.gauge_box = gauge_boxCode
self.dial_centers = dial_centersCode
self.dial_radius = dial_radiusCode
self.dev = devCode
self.tempfile = tempfileCode
self.debug = debugCode
self.debug_nocap = debug_nocapCode
self.debug_logcappath = debug_logcappathCode
Code
def get_reading(self):Python
"""Snap a picture and process a new reading. Returns (value,"""Code
self.snap()Code
self.reading = 0Code
self.cur_time = time.time()Code
Code
da = self.dial_angles = {}Code
cv = self.dial_values = {}Code
Code
self.dials.save('0_dials.jpeg')Code
Code
dr = self.dial_radiusCode
for (factor, (dx,dy,rot)) in dial_centers.items():Code
# crop and enhance the dial imageCode
#Code
#FIXME: better thresholding techniques should certainly beCode
#used, not to mention proper registration of the dialCode
#coordiantes. For now, the camera is well secured, andCode
#lighting constant.Code
im_dial = self.dials.crop( (dx-dr, dy-dr, dx+dr, dy+dr))Code
#im_dial.save('1_crop_%s.jpeg' % factor)Code
im_dial = ImageOps.equalize(im_dial)Code
#im_dial.save('2_eq_%s.jpeg' % factor)Code
im_dial = ImageOps.grayscale(im_dial).point(lambda i: 0 if i < 60 else 255)Code
#im_dial.save('3_thresh_%s.jpeg' % factor)Code
im_dial = im_dial.filter(ImageFilter.ModeFilter)Code
#im_dial.save('4_filter_%s.jpeg' % factor)Code
im_dial = ImageOps.invert(im_dial)Code
#im_dial.save('5_invert_%s.jpeg' % factor)Code
Code
(angle, arcsize) = self.findangle_pie(im_dial, arcsize=15)Code
da[factor] = angle + float(arcsize)/2Code
cv[factor] = self.angle_to_float( da[factor], rot)Code
if self.debug:Code
print "Factor angle: ", factor, angleCode
self.show_pie(im_dial, angle, arcsize)Code
Code
# process the raw valuesCode
self.count_rotations()Code
self.disambiguate_dials()Code
Code
# compute the final valueCode
# factors are per revolution, so divide by tenCode
for factor in (1000000, 100000, 10000, 1000):Code
self.reading += factor/10 * int(self.prev_values[factor])Code
Code
self.reading += 2 * (self.rot_count_adj[2] % 50) + (cv[2] * 0.2)Code
#value += 0.5 * (self.cnt_half % 4)Code
Code
if self.debug:Code
self.show_overlay()Code
return (self.cur_time, self.reading)Code
Code
def disambiguate_dials(self):Code
"Reconcile ambiguous dial values with finer dial readings."Code
cv = self.dial_valuesCode
pv = self.prev_valuesCode
Code
# disambiguate the 2ft dial using the half countCode
if int(cv[2] + 0.2) > int(cv[2]) and (self.rot_count_adj[0.5] % 4) > 1:Code
cv[2] = (int(cv[2]) + 1) % 10Code
else:Code
cv[2] = int(cv[2])Code
Code
# if close to the next value, rely upon the next dial toCode
# disambiguate only really applies to the upper row. IncrementCode
# only onceCode
for factor in (1000, 10000, 100000, 1000000):Code
Code
# increased by >1, or passed zeroCode
if int(cv[factor]) > int(pv[factor]) or (Code
int(pv[factor] > 5) and int(cv[factor]) < 5):Code
# reset the counters, if on the 1000 dialCode
if factor==1000:Code
pv[factor] = cv[factor]Code
self.rot_count_adj[2] += 50 - (self.rot_count_adj[2] % 50)Code
self.rot_count_adj[0.5] += 4 - (self.rot_count_adj[0.5] % 4)Code
# increment only if near a digit, and the next smallerCode
# dial is at a low value.Code
# FIXME: just update whenever the previous dial wrapsCode
elif pv[factor/10] < 5:Code
pv[factor] = cv[factor]Code
elif cv[factor] > (pv[factor] + 0.5) % 10:Code
pv[factor] = cv[factor]Code
returnCode
Code
Code
def count_rotations(self):Code
"""Count rotations of the half and two foot dials. Also,Code
synchronize with the 1000ft dial when it is near a digit."""Code
Code
# Note that if more than about 15 seconds have passed, theCode
# half gauge may have looped. This is not currentlyCode
# consideredCode
Code
t = self.cur_timeCode
cv = self.dial_valuesCode
pv = self.prev_valuesCode
Code
# if no previous value, store the current and move onCode
if self.prev_values is None:Code
self.rot_count_adj = { 0.5: 0, 2: 0}Code
self.rot_count = { 0.5: 0, 2: 0}Code
self.reset_cumm_count()Code
self.prev_values = copy.copy(cv)Code
Code
cv[1000] = int(cv[1000])Code
cv[2] = int(cv[2])Code
returnCode
Code
# increment these counts if they passed zeroCode
for factor in (0.5, 2):Code
# passed zero?Code
if int(pv[factor]) > 5 and int(cv[factor]) < 5:Code
self.rot_count_adj[factor] += 1Code
self.rot_count[factor] += 1Code
self.cumm_count[factor] += 1Code
self.prev_values[factor] = cv[factor]Code
# if more than 0.5 past last, update. 0.5 should be greater than any noiseCode
elif cv[factor] > (pv[factor] + 0.5) % 10:Code
pv[factor] = cv[factor]Code
Code
returnCode
Code
def snap(self, nocapture=False):Python
"""Use v4lctl to capture a new image to disk."""Code
self.cur_time = time.time()Code
if not self.debug_nocap:Code
os.system( "v4lctl -c %s snap jpeg full %s" % (self.dev, self.tempfile))Code
Code
if self.debug_logcappath is not None:Code
shutil.copyfile(Code
self.tempfile,Python
self.debug_logcappath + '/' + str(int(self.cur_time)) + '.jpeg')Code
Code
self.full = Image.open(self.tempfile)Code
#self.full = self.full.rotate(-90)Code
self.dials = self.full.crop(self.gauge_box)Code
returnCode
Code
Code
def angle_to_float(self, angle, rot):Python
"""Convert a gauge angle to a float. rot is either 'cw' or 'ccw'."""Code
if rot == 'ccw':Code
return (-float(angle) / 36 + 7.5) % 10Code
elif rot == 'cw':Code
return (float(angle) / 36 + 2.5) % 10Code
Code
Code
def show_pie(self, img, angle, arcsize):Python
"""Draw a pie slice at the center of an image."""Code
print "Drawing Angle: %d - %d" % (angle, angle+arcsize)Code
imgc = img.copy()Code
imgc = imgc.convert("RGB")Code
draw = ImageDraw.Draw(imgc)Code
draw.pieslice( (0,0,imgc.size[0],imgc.size[1]), angle, angle+arcsize,Code
outline="#00ff00")Code
imgc.show()Code
returnCode
Code
Code
def show_overlay(self):Code
"""Show the current value overlaid on the current image.Code
Mostly for debugging."""Code
img_c = self.full.copy().convert("RGB")Code
draw = ImageDraw.Draw(img_c)Code
draw.rectangle(self.gauge_box, outline='#00FF00')Code
Code
dr = self.dial_radiusCode
bx, by = self.gauge_box[:2]Code
for (factor,(dx,dy,rot)) in self.dial_centers.items():Code
if self.dial_angles is not None:Code
angle = self.dial_angles[factor]Code
else:Code
angle = 0Code
draw.pieslice((dx-dr+bx, dy-dr+by, dx+dr+bx, dy+dr+by),Code
angle, angle-1, outline='#00FF00')Code
if self.dial_values is not None:Code
digit = self.dial_values[factor]Code
draw.text((dx+bx-10, dy+by-dr-15), "%0.2f" % digit, fill='#00FF00')Code
Code
# show only a portion around the bounding boxCode
crop_box = [-30, -30, 30, 30]Code
for (i,val) in enumerate(self.gauge_box): crop_box[i] += valCode
img_c.crop(crop_box)Code
img_c.show()Code
returnCode
Code
def findangle_pie(self, img, arcsize = 10, verbose=False):Python
"""Fine the needle angle by fitting a small pie slice to it"""Code
angles = range(0,360, max(arcsize/2,1))Code
Code
mincnt = img.size[0]*img.size[1]Code
minangle = NoneCode
Code
for angle in angles:Code
imgc = img.copy()Code
draw = ImageDraw.Draw(imgc)Code
draw.pieslice( (0,0,img.size[0],img.size[1]), angle, angle+arcsize, fill=0)Code
Code
count = imgc.histogram()[255]Code
if count < mincnt:Code
mincnt = countCode
minangle = angleCode
Code
if self.debug and verbose:Code
print "Angle, count:", angle, countCode
self.show_pie(img, angle, arcsize)Code
Code
Code
return (minangle, arcsize)Code
Code
# This didn't work so well...Code
def findangle_line(self, img):Code
xs = [float(a) * 20 for a in range(-10,10)]Code
ys = [float(a) * 20 for a in range(-10,10)]Code
Code
mincnt = img.size[0]*img.size[1]Code
minoffset = (None,None)Code
Code
center = tuple([a / 2 for a in img.size])Code
for x_off in xs:Code
for y_off in ys:Code
imgc = img.copy()Code
draw = ImageDraw.Draw(imgc)Code
endpoint = (center[0] + x_off,Code
center[1] + y_off)Code
draw.line( (center, endpoint), fill=0)Code
Code
count = imgc.histogram()[255]Code
print "min, count:", mincnt, countCode
if count < mincnt:Code
mincnt = countCode
minoffset = (x_off, y_off)Code
print "x_off, y_off:", x_off, y_offCode
imgc.show()Code
returnCode
Code
Code
if __name__ == '__main__':Code
# hardcoded coordinates of an arbitrary bounding box to containingCode
# the dials, dial centers, and the dial radius.Code
gb = (30, 275, 330, 450)Code
dial_centers = {1000000 : (59, 48, 'ccw'),Code
100000 : (126, 47, 'cw'),Code
10000 : (193, 47, 'ccw'),Code
1000 : (260, 46, 'cw'),Code
2 : (39, 137, 'ccw'),Code
0.5 : (112, 137, 'ccw')}Code
Code
dial_radius = 31Code
Code
# Print debug information while parsing, and display imagesCode
debug=FalseCode
Code
# Don't capture new images. Use temp.jpeg from the current directoryCode
debug_nocap=TrueCode
Code
# Store captured images in this pathCode
debug_logcappath=os.path.expandvars('$HOME/tmp/images/')Code
Code
# Initialize the capture classCode
c_cap = capture(gb, dial_centers, dial_radius, debug=debug,Code
debug_nocap=debug_nocap, debug_logcappath=debug_logcappath)Code
Code
t_last_cumm = NoneCode
t_last = NoneCode
value_last = NoneCode
dial_last = NoneCode
Code
log_out = open("meter.out",'a', buffering=1)Code
Code
while True:Code
(t, value) = c_cap.get_reading()Code
t = int(t)Code
dial_values = c_cap.dial_valuesCode
prev_values = c_cap.prev_valuesCode
Code
if dial_last is None or value != value_last:Code
print dial_valuesCode
t_last = tCode
dial_last = dial_valuesCode
value_last = valueCode
print >> log_out,"%d %0.2f - %0.3f - %0.3f %d %d - %0.3f %d %d" % (Code
t, value,Code
prev_values[1000],Code
prev_values[2], c_cap.rot_count_adj[2], c_cap.rot_count[2],Code
prev_values[0.5], c_cap.rot_count_adj[0.5], c_cap.rot_count[0.5])Code
if debug_nocap: break
tejal bhesaniya50 pointsPosted Aug 6, 2012, 10:46 PM EDT