def __init__(self):
if len(sys.argv) < 2:
print('Usage: calibration <directory> [<filename>]')
print('The supplied directory should contain the calibration images.')
sys.exit(1)
size = 640
self.path = sys.argv[1]
self.image_window = 'Image Calibration'
self.sky_window = 'Sky Calibration'
self.tb_image_switch = 'image'
self.tb_max_mag = 'maximum magnitude'
self.save_file_name = 'data'
self.selected_star = None
self.selected_color = (0, 0, 255)
self.marked_color = (0, 255, 0)
self.circle_radius = 5
self.max_mag = 4
self.renderer = SkyRenderer(size)
try:
self.calibrator = Calibrator(SkyCameraFile.glob(self.path), EarthLocation(lat=Configuration.latitude, lon=Configuration.longitude, height=Configuration.elevation))
except Exception as e:
print(e.message)
sys.exit(2)
if len(sys.argv) > 2:
self.save_file_name = sys.argv[2]
if os.path.exists(self.save_file_name):
self.calibrator.load(self.save_file_name)
cv2.namedWindow(self.image_window, cv2.WINDOW_AUTOSIZE)
cv2.namedWindow(self.sky_window, cv2.WINDOW_AUTOSIZE)
self.selectImage(0)
cv2.setMouseCallback(self.image_window, self.imageMouseCallback)
cv2.setMouseCallback(self.sky_window, self.skyMouseCallback)
cv2.createTrackbar(self.tb_image_switch, self.image_window, 0, len(self.calibrator.files) - 1, self.selectImage)
cv2.createTrackbar(self.tb_max_mag, self.sky_window, self.max_mag, 6, self.setMaxMag)
python类setMouseCallback()的实例源码
camshift.py 文件源码
项目:Artificial-Intelligence-with-Python
作者: PacktPublishing
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def __init__(self, scaling_factor=0.5):
# Initialize the video capture object
self.cap = cv2.VideoCapture(0)
# Capture the frame from the webcam
_, self.frame = self.cap.read()
# Scaling factor for the captured frame
self.scaling_factor = scaling_factor
# Resize the frame
self.frame = cv2.resize(self.frame, None,
fx=self.scaling_factor, fy=self.scaling_factor,
interpolation=cv2.INTER_AREA)
# Create a window to display the frame
cv2.namedWindow('Object Tracker')
# Set the mouse callback function to track the mouse
cv2.setMouseCallback('Object Tracker', self.mouse_event)
# Initialize variable related to rectangular region selection
self.selection = None
# Initialize variable related to starting position
self.drag_start = None
# Initialize variable related to the state of tracking
self.tracking_state = 0
# Define a method to track the mouse events
def Crop(img,title):
def onmouse(event,x,y,flags,param):
global ix,iy,roi,drawing
# Draw Rectangle
if event == cv2.EVENT_RBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,abs(ix-x),abs(iy-y))
elif event == cv2.EVENT_RBUTTONUP:
drawing = False
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,x,y)
roi.extend(rect)
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.setMouseCallback(title,onmouse)
print ("Right click and hold to draw a single rectangle ROI, beginning at the top left corner of the desired area. A blue box should appear. Hit esc to exit screen. Window can be resized by selecting borders.")
while True:
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.imshow(title,img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
print(roi)
return(roi)
def Crop(img,title):
def onmouse(event,x,y,flags,param):
global ix,iy,roi,drawing
# Draw Rectangle
if event == cv2.EVENT_RBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,abs(ix-x),abs(iy-y))
elif event == cv2.EVENT_RBUTTONUP:
drawing = False
cv2.rectangle(img,(ix,iy),(x,y),BLUE,-1)
rect = (ix,iy,x,y)
roi.extend(rect)
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.setMouseCallback(title,onmouse)
print ("Right click and hold to draw a single rectangle ROI, beginning at the top left corner of the desired area. A blue box should appear. Hit esc to exit screen. Window can be resized by selecting borders.")
while True:
cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.imshow(title,img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
print(roi)
return(roi)
def __init__(self, windowname, dests, colors_func):
self.prev_pt = None
self.windowname = windowname
self.dests = dests
self.colors_func = colors_func
self.dirty = False
self.show()
cv2.setMouseCallback(self.windowname, self.on_mouse)
def __init__(self, win, callback):
self.win = win
self.callback = callback
cv2.setMouseCallback(win, self.onmouse)
self.drag_start = None
self.drag_rect = None
def setCorners(self):
name_window = 'Set Corners'
cv2.namedWindow(name_window)
cv2.setMouseCallback(name_window, saveTabletCorners)
cap = cv2.VideoCapture(0)
ret, frame_from = cap.read()
TTablet.m_CornersX = []
TTablet.m_CornersY = []
TTablet.m_AddFrame = np.zeros(frame_from.shape, np.uint8)
#print ("start setCorners")
while(cap.isOpened()):
ret, frame_from = cap.read()
frame_from = cv2.flip(frame_from, -1)
frame = cv2.add(TTablet.m_AddFrame, frame_from)
if ret==True:
cv2.imshow(name_window,frame)
#print ("fasdfasdf")
if cv2.waitKey(1) & (len(TTablet.m_CornersX) > 3):
break
else:
break
# Release everything if job is finished
cap.release()
#out.release()
cv2.destroyAllWindows()
def get_user_selected_point(image):
global point
point = (-1,-1)
cv2.setMouseCallback(MAZE_NAME,get_mouse_point)
print("Press any key once you have selected your point")
while point == (-1,-1):
cv2.waitKey(0)
if(point == (-1,-1)):
print("Invalid pont, please try again")
return point[0],point[1]
def __init__(self, windowname, dests, colors_func):
self.prev_pt = None
self.windowname = windowname
self.dests = dests
self.colors_func = colors_func
self.dirty = False
self.show()
cv2.setMouseCallback(self.windowname, self.on_mouse)
def __init__(self, win, callback):
self.win = win
self.callback = callback
cv2.setMouseCallback(win, self.onmouse)
self.drag_start = None
self.drag_rect = None
RRT_Scan.py 文件源码
项目:Rapidly-Exploring-Random-Tree-Star-Scan
作者: vampcoder
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def getSourceAndGoal(self):
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.draw_circle)
cv2.imshow('image', img)
cv2.waitKey(0)
RRTstar_Scan1.py 文件源码
项目:Rapidly-Exploring-Random-Tree-Star-Scan
作者: vampcoder
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def getSourceAndGoal(self):
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.draw_circle)
cv2.imshow('image', img)
cv2.waitKey(0)
RRT_Scan_final.py 文件源码
项目:Rapidly-Exploring-Random-Tree-Star-Scan
作者: vampcoder
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def getSourceAndGoal(self):
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.draw_circle)
cv2.imshow('image', img)
cv2.waitKey(0)
RRTstar_Scan.py 文件源码
项目:Rapidly-Exploring-Random-Tree-Star-Scan
作者: vampcoder
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def getSourceAndGoal(self):
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.draw_circle)
cv2.imshow('image', img)
cv2.waitKey(0)
def main():
img = None
main_win = Windows_handler.WinHandler(title='Nox',class_name='Qt5QWindowIcon')
main_box = main_win.get_bbox()
px_handler = Pixel_handler.PixelSearch(win_handler=main_win)
mouse = Mouse_handler.MouseMovement(window_handler=main_win)
main_win.init_window()
cv2.namedWindow('image_name')
cv2.namedWindow('config')
while True:
img = px_handler.grab_window(bbox=main_box)
img = px_handler.img_to_numpy(img,compound=False)
img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
orb = cv2.ORB_create()
kp = orb.detect(img, None)
kp, des = orb.compute(img, kp)
img2 = cv2.drawKeypoints(img, kp)
cv2.imshow('image_name',img2)
cv2.setMouseCallback('image_name', mouse_event, param=img)
k = cv2.waitKey(1)
if k == ord('q'): # wait for ESC key to exit
cv2.destroyAllWindows()
quit(0)
def test(m):
class DrawingState:
def __init__(self):
self.x_prev = 0
self.y_prev = 0
self.drawing = False
self.update = True
def interactive_drawing(event, x, y, flags, param):
image = param[0]
state = param[1]
if event == cv2.EVENT_LBUTTONDOWN:
state.drawing = True
state.x_prev, state.y_prev = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if state.drawing:
cv2.line(image, (state.x_prev, state.y_prev), (x, y), (1, 1, 1), 1)
state.x_prev = x
state.y_prev = y
state.update = True
elif event == cv2.EVENT_LBUTTONUP:
state.drawing = False
elif event == cv2.EVENT_RBUTTONDOWN:
image.fill(0)
state.update = True
cv2.namedWindow('Canvas')
image_input = np.zeros((FLAGS.input_height, FLAGS.input_width, 3), np.float32)
state = DrawingState()
cv2.setMouseCallback('Canvas', interactive_drawing, [image_input, state])
while cv2.getWindowProperty('Canvas', 0) >= 0:
if state.update:
reshaped_image_input = np.array([image_input])
image_output = m.test(reshaped_image_input)
concatenated = np.concatenate((image_input, image_output[0]), axis=1)
color_converted = cv2.cvtColor(concatenated, cv2.COLOR_RGB2BGR)
cv2.imshow('Canvas', color_converted)
state.update = False
k = cv2.waitKey(1) & 0xFF
if k == 27: # esc
break
cv2.destroyAllWindows()
def main(wall_file = None):
global image, draw_tile, clone
image = np.zeros((600, 600, 3), dtype = "uint8")
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", mouse_callback)
if wall_file:
_load_wall(wall_file)
# keep looping until the 'q' key is pressed
while True:
# display the image and wait for a keypress
cv2.imshow("image", image)
key = cv2.waitKey(1) & 0xFF
# if the 'r' key is pressed, reset the cropping region
if key == ord("r"):
image = clone.copy()
elif key == ord("g"):
print("savig the .piwall file")
target = open(generated_piwall, 'w')
dotpiwall = DotPiwall("test", wall)
#print(str(dotpiwall))
target.write(str(dotpiwall))
target.close()
elif key == ord("d"):
draw_tile = not draw_tile
elif key == ord("h"):
help_popup()
elif key == ord("s"):
save_wall_popup()
elif key == ord("l"):
load_wall_popup()
elif key == ord("w"):
print(wall)
print('gui tiles %d' % len(tiles))
# if the 'c' key is pressed, break from the loop
elif key == ord("c") or key == ord("q"):
break
# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(refPt) == 2:
roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
cv2.imshow("ROI", roi)
cv2.waitKey(0)
# close all open windows
cv2.destroyAllWindows()
def _find_array_button_thing(self):
""" Find the array button on the solar array box """
""" This uses color to determine if we have a choke """
lower = np.array([0, 0, 60], dtype = "uint8")
upper = np.array([20, 20, 255], dtype = "uint8")
mask = cv2.inRange(self.img, lower, upper)
blurred = cv2.GaussianBlur(mask, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if is_cv2() else contours[1]
debug_img = None
if self.debug:
debug_img = self.img.copy()
button_box = None
for c in contours:
box = cv2.boundingRect(c)
if button_box is None:
button_box = box
else:
button_box = self._union_box(deepcopy(button_box), box)
if button_box is None:
return
top,bottom,left,right,center = self.find_dimensions(np.int0(np.array(self._bound_to_boxpoints(button_box))))
if top is None or left is None or center is None:
return None
height = self.find_distance(top, bottom)
width = self.find_distance(left, right)
if self.debug:
for c in contours:
cv2.drawContours(debug_img, [c], -1, (0, 255, 0), 2)
cv2.circle(debug_img, top, 5, (255, 255, 0))
cv2.circle(debug_img, bottom, 5, (255, 255, 0))
cv2.circle(debug_img, left, 5, (255, 255, 0))
cv2.circle(debug_img, right, 5, (255, 255, 0))
cv2.rectangle(debug_img, (button_box[0], button_box[1]),
(button_box[0] + button_box[2], button_box[1] + button_box[3]), (128, 0, 128), 2)
#cv2.circle(debug_img, center, 5, (255, 255, 0))
cv2.imshow("button picture", debug_img)
cv2.setMouseCallback("button picture", self.handle_mouse)
cv2.waitKey(0)
cv2.destroyAllWindows()
self.array_button = Thing(height, width, center, None)
self.array_button.set_array_button()
self.array_button.computed_center = self.compute_center(left, right, top, bottom)
self.things.append(self.array_button)
def _find_choke_thing(self):
""" Find the choke at the solar array box """
""" This uses color to determine if we have a choke """
lower = np.array([128, 0, 0], dtype = "uint8")
upper = np.array([255, 10, 20], dtype = "uint8")
mask = cv2.inRange(self.img, lower, upper)
blurred = cv2.GaussianBlur(mask, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if is_cv2() else contours[1]
# Note: you can get your view of the choke cut; so you see an end as 2 contours.
# In a dream world, we would combine two small controus close together.
# But for now, we just operate with the two biggest contours
sorted_contours = sorted(contours, cmp=lambda a,b: int(cv2.contourArea(b)) - int(cv2.contourArea(a)))
if len(sorted_contours) >= 2:
thing1 = self._find_a_thing(sorted_contours[0], 0, 0.1, 0, 0.1, 99.0)
thing2 = self._find_a_thing(sorted_contours[1], 0, 0.1, 0, 0.1, 99.0)
if thing1 is not None and thing2 is not None:
print "We have a choke!"
box1 = cv2.boundingRect(sorted_contours[0])
box2 = cv2.boundingRect(sorted_contours[1])
if box1[0] > box2[0]:
inner = thing1
outer = thing2
else:
inner = thing2
outer = thing1
inner.set_choke_inner()
self.things.append(inner)
self.choke_inner = inner
outer.set_choke_outer()
self.things.append(outer)
self.choke_outer = outer
if self.debug:
debug_img = self.img.copy()
for c in sorted_contours:
cv2.drawContours(debug_img, [c], -1, (0, 255, 0), 2)
cv2.imshow("choke picture", debug_img)
cv2.setMouseCallback("choke picture", self.handle_mouse)
cv2.waitKey(0)
cv2.destroyAllWindows()
def _find_habitat_things(self):
""" Find interesting objects in the habitat world """
self._find_repair_button_thing()
# Start by grey scale, blur, and thresholding
gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
# find contours in the thresholded image
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if is_cv2() else contours[1]
debug_img = self.img.copy()
for c in contours:
thing = self._find_a_thing(c, self.MINIMUM_TOOL_LENGTH, self.MAXIMUM_TOOL_LENGTH,
self.MINIMUM_TOOL_WIDTH, self.MAXIMUM_TOOL_WIDTH,
self.TOOL_MUST_BE_WITHIN, debug_img)
if thing is None:
continue
x,y,w,h = cv2.boundingRect(c)
detector_center, up = self.is_detector(self.img[y:y+h,x:x+w].copy())
if detector_center is not None:
adjusted_detector = (int(detector_center[0] + x), int(detector_center[1] + y))
thing.set_detector(adjusted_detector, up)
self.things.append(thing)
self.leak_detector = thing
repair_center, up = self.is_repair_tool(self.img[y:y+h,x:x+w].copy())
if repair_center is not None:
adjusted_repair = (int(repair_center[0] + x), int(repair_center[1] + y))
thing.set_repair_tool(adjusted_repair, up)
self.things.append(thing)
self.repair_tool = thing
if self.debug:
for c in contours:
cv2.drawContours(debug_img, [c], -1, (0, 255, 0), 2)
cv2.imshow("habitat things", debug_img)
cv2.setMouseCallback("habitat things", self.handle_mouse)
cv2.waitKey(0)
cv2.destroyAllWindows()