如何使用opencv在python中的图像上制作自由手形状(随机) [英] How to make a free hand shape(random) on an image in python using opencv
问题描述
要在区域中应用边界填充,我需要在python-opencv中使用鼠标绘制自由形状(随机)
To apply boundary fill in a region i need to draw a free hand shape(random) using mouse in python-opencv
推荐答案
您问过如何使用计算机的鼠标在图片上绘制任何给定者随机形状.这是一个简单的解决方案:
You asked how to draw any giver random shape on a picture using your computer's mouse. Here is a simple solution:
首先,您需要设计一种绘制方法.因此,让我们从 OpenCV:Mouse中启发自己作为画笔" ,其中一种方法用于使用鼠标绘制常见的常规形状,例如圆形或矩形.在您的情况下,您将需要像用一只手一样随机绘制.
First, you will need to design a method that enables you to draw. So let's inspire ourselves from OpenCV: Mouse as a Paint-Brush where a method is used to draw common regular shapes such as a circle or a rectangle using a mouse. In your case, you will need random drawing as you could do with your hand.
因此,使用该方法,您可以使用鼠标绘制点并执行 内插 在它们之间使用 cv2.line()
方法:
So using that method you can draw points using the mouse and perform an interpolation between them using cv2.line()
method:
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
im
是您所阅读的图像,并且您必须始终记住鼠标位置的先前坐标:
Where im
is the image you read and while you must memorize the former coordinates of the mouse position all the time:
current_former_x = former_x
current_former_y = former_y
完整的OpenCV程序:
这是代码.不要犹豫,评论任何您不了解的内容:
Full OpenCV program:
Here is the code. Do not hesitate to comment anything you wouldn't understand:
'''
Created on Apr 3, 2016
@author: Bill BEGUERADJ
'''
import cv2
import numpy as np
drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve
# mouse callback function
def begueradj_draw(event,former_x,former_y,flags,param):
global current_former_x,current_former_y,drawing, mode
if event==cv2.EVENT_LBUTTONDOWN:
drawing=True
current_former_x,current_former_y=former_x,former_y
elif event==cv2.EVENT_MOUSEMOVE:
if drawing==True:
if mode==True:
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
current_former_x = former_x
current_former_y = former_y
#print former_x,former_y
elif event==cv2.EVENT_LBUTTONUP:
drawing=False
if mode==True:
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
current_former_x = former_x
current_former_y = former_y
return former_x,former_y
im = cv2.imread("darwin.jpg")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',begueradj_draw)
while(1):
cv2.imshow('Bill BEGUERADJ OpenCV',im)
k=cv2.waitKey(1)&0xFF
if k==27:
break
cv2.destroyAllWindows()
演示:
这篇关于如何使用opencv在python中的图像上制作自由手形状(随机)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!