我有一个程序可以选择一个区域并用特定的颜色填充它。 我需要重建图像。 请帮忙。 提前谢谢。
选择边界和填充的程序在
之下import cv2
import numpy as np
import sys
def is_equal(a, b):
_equal = a[0]==b[0] and a[1]==b[1] and a[2]==b[2]
return _equal
sys.setrecursionlimit(30000)
def boundary_fill(src, x, y, fill_color, boundary_color):
try:
color_at_xy = src[y, x]
except (IndexError,RuntimeError):
return
if not is_equal(color_at_xy,fill_color) and not is_equal(color_at_xy,boundary_color):
src[y, x] = fill_color
boundary_fill(src, x + 1, y, fill_color, boundary_color)
boundary_fill(src, x - 1, y, fill_color, boundary_color)
boundary_fill(src, x, y - 1, fill_color, boundary_color)
boundary_fill(src, x, y + 1, fill_color, boundary_color)
boundary_fill(src, x + 1, y - 1, fill_color, boundary_color)
boundary_fill(src, x + 1, y + 1, fill_color, boundary_color)
boundary_fill(src, x - 1, y - 1, fill_color, boundary_color)
boundary_fill(src, x - 1, y + 1, fill_color, boundary_color)
ix,iy = -1,-1
drawing = False # true if mouse is pressed
pressed = False
boundary_mode = True
# mouse callback function
def draw_boundary(event,former_x,former_y,flags,param):
global current_former_x,current_former_y,drawing, boundary_mode, pressed
if boundary_mode:
if event==cv2.EVENT_LBUTTONDOWN:
pressed=True
current_former_x,current_former_y=former_x,former_y
elif event==cv2.EVENT_MOUSEMOVE:
if pressed == True:
drawing = True
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),2)
current_former_x = former_x
current_former_y = former_y
elif event==cv2.EVENT_LBUTTONUP:
if drawing:
drawing=False
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),2)
current_former_x = former_x
current_former_y = former_y
pressed = False
elif event == cv2.EVENT_LBUTTONDBLCLK:
print ix,iy
boundary_fill(im, former_x, former_y, (255,255,255), (0,0,255))
return former_x,former_y
if __name__ == "__main__":
render = True
im = cv2.imread("src.jpg")
cv2.namedWindow("Bound")
cv2.setMouseCallback('Bound',draw_boundary)
while(render):
cv2.imshow('Bound',im)
k = cv2.waitKey(1)&0xFF
if k==27:
render = False
cv2.destroyAllWindows()