官术网_书友最值得收藏!

Basic shapes – lines, rectangles, and circles

In the next example, we are going to see how to draw basic shapes in OpenCV. These basic shapes include lines, rectangles, and circles, which are the most common and simple shapes to draw. The first step is to create an image where the shapes will be drawn. To this end, a 400  400 image with the 3 channels (to properly display a BGR image) and a uint8 type (8-bit unsigned integers) will be created:

# We create the canvas to draw: 400 x 400 pixels, 3 channels, uint8 (8-bit unsigned integers)
# We set the background to black using np.zeros()
image = np.zeros((400, 400, 3), dtype="uint8")

We set the background to light gray using the colors dictionary:

# If you want another background color, you can do the following:
image[:] = colors['light_gray']

This canvas (or image) is shown in the next screenshot:

Now, we are ready to draw the basic shapes. It should be noted that most drawing functions that OpenCV provides have common parameters. For the sake of simplicity, these parameters are briefly introduced here:

  • img: It is the image where the shape will be drawn.
  • color: It is the color (BGR triplet) used to draw the shape.
  • thickness: If this value is positive, it is the thickness of the shape outline. Otherwise, a filled shape will be drawn.
  • lineType: It is the type of the shape boundary. OpenCV provides three types of line:
    • cv2.LINE_4: This means four-connected lines
    • cv2.LINE_8: This means eight-connected lines
    • cv2.LINE_AA: This means an anti-aliased line
  • shift: This indicates the number of fractional bits in connection with the coordinates of some points defining the shape.

In connection with the aforementioned parameters, the cv2.LINE_AA option for lineType produces a much better quality drawing (for example, when drawing text), but it is slower to draw. So, this consideration should be taken into account. Both the eight-connected and the four-connected lines, which are non-antialiased lines, are drawn with the Bresenham algorithm. For the anti-aliased line type, the Gaussian filtering algorithm is used. Additionally, the shift parameter is necessary because many drawing functions can't deal with sub-pixel accuracy. For simplicity in our examples, we are going to work with integer coordinates. Therefore, this value will be set to 0 (shift = 0). However to give you a complete understanding, an example of how to use the shift parameter will also be provided.

Remember that, for all the examples included in this section, a canvas has been created to draw all the shapes. This canvas is a  400 x 400 pixel image, with a light gray background. See the previous screenshot, which shows this canvas.
主站蜘蛛池模板: 咸丰县| 曲沃县| 龙泉市| 威海市| 岢岚县| 甘肃省| 濮阳市| 桦甸市| 绵阳市| 鸡东县| 平凉市| 长沙县| 镇康县| 怀仁县| 中方县| 石景山区| 万年县| 图木舒克市| 鸡东县| 沅江市| 墨竹工卡县| 图们市| 荆州市| 新乡县| 谷城县| 高州市| 当雄县| 玛纳斯县| 土默特右旗| 铜陵市| 湖口县| 衡南县| 盘山县| 石阡县| 合江县| 淮滨县| 闽侯县| 嵊州市| 淮南市| 泾源县| 高台县|