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

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.
主站蜘蛛池模板: 芜湖市| 农安县| 武清区| 文山县| 灌阳县| 抚松县| 贡觉县| 宕昌县| 丽水市| 旌德县| 乌恰县| 儋州市| 木里| 涞源县| 长治县| 名山县| 富顺县| 兴化市| 大丰市| 岚皋县| 耒阳市| 罗江县| 天柱县| 内黄县| 湾仔区| 宁陕县| 平邑县| 靖边县| 永宁县| 北票市| 博罗县| 高要市| 开封市| 桂林市| 徐州市| 东兰县| 临湘市| 聂拉木县| 建阳市| 正安县| 永春县|