OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision, originally developed by an Intel research center and now open source.

TouchDesigner comes pre-installed with OpenCV 4.5 (including contributed modules), and numpy which interface with TouchDesigner's Python 3.7.2, making it possible for TouchDesigner to access the OpenCV functions directly.

OpenCV is used in the Script TOP, Blob Track TOP and camSchnappr.

Using OpenCV with pythonedit

Testing OpenCVedit

  • open TouchDesigner
  • open the Textport with Alt+t
  • run following commands:
TouchDesigner  Build 2020.44350 compile on Thu Dec  3 19:21:39 2020
Python 3.7.2 (heads/3.7-Derivative:052feb9e72, Mar  7 2019, 16:29:45) [MSC v.1900 64 bit (AMD64)]

python >>> import cv2
python >>> cv2.__version__
  • if the output is '4.5.0' and no errors, OpenCV is working properly.

Textures to numpyArraysedit

Every TOP can directly be converted into a NumPy Array by calling the myTop.numpyArray() Method (Also see: TOP Class#Methods)

NumPy arrays are the default data structure openCV saves its data in. In general NumPy can be understood as a library for Python to support large, multi-dimensional arrays and matricies, along with a large collection of high level functions to operate on these arrays. (Compare: NumPy)

Example: Applying a colormap to a Textureedit

The following example is the content of a Script TOP. The OpenCV function cv2.applyColorMap() takes as input a monochrome image as well as a reference to a predefined colormap essentially doing what the Lookup TOP does in TouchDesigner. More information can be found here: ColorMaps in OpenCV

 1def onCook(scriptOp):
 2	# grab the input to the scriptTOP with a frame delayed
 3    # for faster operation (compare TopTo CHOP)
 4	input = scriptOp.inputs[0].numpyArray(delayed=True)
 6	# do we have a image ready?
 7    # the first frame will be None as we are getting things a frame later.
 8	if not input is None: 
 9		# extract the red channel and convert to uint8
10		sChan = cv2.extractChannel(input,0)*255
11		sChan = sChan.astype('uint8')
13		# apply a colormap to the red channel
14		output = cv2.applyColorMap(sChan, cv2.COLORMAP_TWILIGHT_SHIFTED)
15        # output the numpyarray to the Script TOP
16		scriptOp.copyNumpyArray(output)
17	return

Example: Finding Features in a Textureedit

The following example is the content of a Script CHOP. First, parameters for the Script CHOP are specified.

For each cook of the Script CHOP, the operator specified in the Top custom parameter is read into a numPy array and then passed on to an openCV function called goodFeaturesToTrack.

Note: The referenced TOP should be a monochrom image. Converting color textures to grayscale can be done using the Monochrome TOP. Doing so, and using the Luminance function as the convertion, makes it unnecessary to do this step in the script (many openCV functions expect a grayscale image as input).

The resulting output can be used in an Instancing setup.

 1# me - this DAT
 2# scriptOp - the OP which is cooking
 4# press 'Setup Parameters' in the OP to call this function to re-create the parameters.
 5def onSetupParameters(scriptOp):
 6	# create a custom page
 7	page = scriptOp.appendCustomPage('Good Features')
 9	# create a custom TOP reference parameter
10	topPar = page.appendTOP('Top', label='TOP (monochrome)')
12	# create a custom parameter to specify number of features to detect
13	p = page.appendInt('Features', label='Number of Features')
14	p[0].default = 25
15	p[0].normMin = 1
16	p[0].normMax = 250
18	# create a custom parameter to specify minimum quality level
19	# under which detected features would be rejected
20	p = page.appendFloat('Quality', label='Minimum Quality Level')
21	p[0].default = 0.01
22	p[0].normMin = 0.001
23	p[0].normMax = 1
25	# create a custom parameter to specify the minimum distance
26	# between detected features
27	p = page.appendInt('Distance', label='Minimum Distance')
28	p[0].default = 10
29	p[0].normMin = 1
30	p[0].normMax = 1200
31	return
33# called whenever custom pulse parameter is pushed
34def onPulse(par):
35	return
37import numpy as np
38import cv2
40def onCook(scriptOp):
41	scriptOp.clear()
43	# read in parameters to see how many features to detect
44	topRef = scriptOp.par.Top.eval()
45	features = scriptOp.par.Features
46	quality = scriptOp.par.Quality
47	distance = scriptOp.par.Distance
49	# default values
50	xVals = []
51	yVals = []
52	corners = []
54	if topRef:
55		# read top as numpyArray
56		img = topRef.numpyArray()
58		# since we are reading from a gray scale TOP, throw out everything but red channel
59		# we also can skip the cv2.cvtColor function you would see here otherwise for converting a color image to gray scale
60		img = img[:,:,:1]
62		# run goodFeaturesToTrack openCV function
63		#
64		corners = cv2.goodFeaturesToTrack(img,features,quality,distance)
66		# slice array to have x and y positions split into 2 variables
67		xVals = corners[:,:,0:1]
68		yVals = corners[:,:,1:2]
70	# setup the scriptOp with 2 channels
71	# also set length to number of features that were detected
72	scriptOp.rate = me.time.rate
73	scriptOp.numSamples = len(corners)
74	tx = scriptOp.appendChan('tx')
75	ty = scriptOp.appendChan('ty')
77	# assign values to channels
78	tx.vals = xVals
79	ty.vals = yVals
80	return

Textures to CUDA Memoryedit

Next Stepsedit

There is a selection of introductory tutorials on the OpenCV website and OpenCV Tutorials

Using OpenCV with Custom Operatorsedit

TouchDesigner includes the full set of OpenCV libraries and includes necessary to develop Custom Operators that make use of OpenCV 4.5

In the TouchDesigner GitHub repository "Custom Operator Samples" multiple examples in the TOP family make use of OpenCV:

OpenCV C++ Documentation is here.

OpenCV License Agreementedit

TouchDesigner uses parts of OpenCV (the Blob Track TOP) under the following license.

Intel License Agreement.

Copyright (C) 2000, Intel Corporation, rights reserved. Third party copyrights are property of their respective owners.

Redistribution of OpenCV and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistribution's of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistribution's in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • The name of Intel Corporation may not be used to endorse or promote products derived from this software without specific prior written permission.

The OpenCV software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the Intel Corporation or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.