Monday, 19 April 2021

opencv 33 generate ArUco marker

 ArUco markers are used for:
  • Camera calibration
  • Object size estimation
  • Measuring the distance between camera and object
  • 3D position
  • Object orientation
  • Robotics and autonomous navigation
ArUco Tags ID 0 - 9
#main.py
import numpy as np
import argparse
import cv2
import sys

ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DICT_4X4_250": cv2.aruco.DICT_4X4_250,
"DICT_4X4_1000": cv2.aruco.DICT_4X4_1000,
"DICT_5X5_50": cv2.aruco.DICT_5X5_50,
"DICT_5X5_100": cv2.aruco.DICT_5X5_100,
"DICT_5X5_250": cv2.aruco.DICT_5X5_250,
"DICT_5X5_1000": cv2.aruco.DICT_5X5_1000,
"DICT_6X6_50": cv2.aruco.DICT_6X6_50,
"DICT_6X6_100": cv2.aruco.DICT_6X6_100,
"DICT_6X6_250": cv2.aruco.DICT_6X6_250,
"DICT_6X6_1000": cv2.aruco.DICT_6X6_1000,
"DICT_7X7_50": cv2.aruco.DICT_7X7_50,
"DICT_7X7_100": cv2.aruco.DICT_7X7_100,
"DICT_7X7_250": cv2.aruco.DICT_7X7_250,
"DICT_7X7_1000": cv2.aruco.DICT_7X7_1000,
"DICT_ARUCO_ORIGINAL": cv2.aruco.DICT_ARUCO_ORIGINAL,
"DICT_APRILTAG_16h5": cv2.aruco.DICT_APRILTAG_16h5,
"DICT_APRILTAG_25h9": cv2.aruco.DICT_APRILTAG_25h9,
"DICT_APRILTAG_36h10": cv2.aruco.DICT_APRILTAG_36h10,
"DICT_APRILTAG_36h11": cv2.aruco.DICT_APRILTAG_36h11
}

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--id", type=int, required=True,
help="ID of ArUCo tag to generate")
ap.add_argument("-t", "--type", type=str,
default="DICT_ARUCO_ORIGINAL",
help="type of ArUCo tag to generate")
args = vars(ap.parse_args())

# verify that the supplied ArUCo tag exists and is supported by OpenCV
if ARUCO_DICT.get(args["type"], None) is None:
print("[INFO] ArUCo tag of '{}' is not supported".format(
args["type"]))
sys.exit(0)

# load the ArUCo dictionary
arucoDict = cv2.aruco.Dictionary_get(ARUCO_DICT[args["type"]])

# allocate memory for the output ArUCo tag and then draw the ArUCo
# tag on the output image
print("[INFO] generating ArUCo tag type '{}' with ID '{}'".format(
args["type"], args["id"]))
tag = np.zeros((300, 300, 1), dtype="uint8")

#drawMarker( dictionary, id, size, image, border bits)
cv2.aruco.drawMarker(arucoDict, args["id"], 300, tag, 1)

# write the generated ArUCo tag to disk and then display it to our
# screen
cv2.imwrite("assets/aurco.png", tag)
name = "ArUCo ID " + str(args["id"])
cv2.imshow(name, tag)
cv2.waitKey(0)

--------------------------
#logs
(venv) C:\Users\zchen\PycharmProjects\opencv>python aruco.py --id 9 --type DICT_5X5_100
[INFO] generating ArUCo tag type 'DICT_5X5_100' with ID '9'

reference:

C-17, F-22, MQ8

Sunday, 18 April 2021

West Virginia tour

电动大货车

 

今年油价涨的真的是太快了,去年疫情92号汽油仅5块多,而如今,大多数城市地区92号汽油已经突破6.6元/L,很多人已经是尽量能不开车,如果是大排量发动机,比如纳智捷,估计这些车主宁愿坐公交,骑电动车也不想开车。但是,正因为油价涨了,从去年开始,新能源电动车的销量与日俱增,比亚迪汉EV、特斯拉Model 3、理想ONE的销量销量都是居高不下,前两款车型的销量多次排进同级别车型销量前五,理想ONE更是多次取得中大型SUV销量冠军,新能源汽车真的很有可能淘汰燃油车。

相比家用车,大货车的油耗确实称得上“油老虎”,所以这也养出了很多“油耗子”。在公路上行驶的大货车基本都对油箱进行改装过,两侧都有硕大容积的油箱,加一次油少说五六千,多了八九千,过万都是很正常的,所以很多大货车司机在停车休息的时候,都会安排人看好油箱,甚至专门养只狗看管。大货车司机为什么不喜欢踩刹车,还不是因为停车起步油耗会增加,所以很多司机在临近红绿灯的时候都会采取滑行,避免重车起步。家用车、公交车都开始采用电动车,而马斯克又来搅局了,造出电动大货车,6秒破百续航超800公里,售价100万起。

首先,先来解释一下,为什么特斯拉造的电动大货车会让人失业?马斯克曾经表示,特斯拉造的电动大货车会搭载和私家车一样的“无人驾驶技术”,当然,也就是代替司机去掌握方向盘,车道保持辅助、主动刹车等等。当然,这样的技术还不足以让人失业,接下来马斯克所表示的这项技术,确实可以帮助企业、物流单位减少人员工资。

新车将会带有“车队模式”,我们都知道,火车之所以能够行驶,都是最前面的机车所带动,而特斯拉造的车足以通过一名驾驶员,在前方驾驶车辆,后方车辆进行功能上的连接,可以进入彻底的“无人驾驶”,车辆变道,系统会检测周围道路状况进行变道,主驾驶车辆减速、刹车,后方车辆也能够完成。是不是足以让人失业?对此你们怎么看,可以在评论区留言。

这款电动大货车的外观造型也是非常富有科技感的,坐姿相对比解放、东风等大货车的坐姿要低些许,所以盲区也会相对减少。而且,整台车乍看之下与和谐号子弹头高速列车极为相似,风阻系数低至0.36,几乎堪比超跑。坐进车内,内饰相对简洁,富有科技感。中间控制主机的驾驶屏幕,因为两侧后视镜采用摄像头,所以都是通过显示器进行显示。如果在国内地区上市销售,很显然这款车必须老老实实装上传统的后视镜,因为我国的法律暂时还不允许。

车内只有一个驾驶位,但是车内的高度惊人高达2米,稍微改装一下就可以设计出上下两层的床铺,即便坐在床上,头顶的距离也不会像火车硬卧那般压抑,更多是像现在的动卧。大货车最注重的就是动力,更何况这是台电动大货车。牵引车头前两个车轮控制转向,后面四个车轮则各自搭载一台电机,据悉动力输出可达到1000P。对此,国外进行了 测试,载重36吨货物百公里加速是20秒,在空车运行情况下,百公里加速不到6秒,远要比咱们的柴油车加速能力更强。

其次,这四台电机都是独立的个体,单个发生故障都可以保证车辆正常行驶,据说这四台电机都可以在160万公里以内做到“零故障”,所以电机的寿命也是非常长的。据马斯克介绍,这台电动大货车会分别推出两个版本,入门续航482公里,进阶续航可达到804公里。当然,这还是最初的打算,马斯克表示电池组也会进行重新设计,从而在提高预计行驶里程。很有可能会实现充电半小时有效行驶643公里,普通大货车加油从排队加油到驶离也得半小时左右,所以这台电动大货车并不会影响运输效率。

Saturday, 17 April 2021

opencv 32 reading book

perspective transform to straighten the book

adaptive threshold to highlight text

detect texts with tesseract
reorder sentences into paragraph

read paragraph with text to speech
#book_reader.py
import cv2
import numpy as np
import imutils
import pytesseract
#import pyttsx3
from gtts import gTTS
from playsound import playsound
import subprocess
import os

pytesseract.pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"

def speak(audioString):
    print(audioString)
    tts = gTTS(text=audioString, lang='en')
    tts.save("assets/audio.mp3")


    wmp = r"C:\Program Files (x86)\Windows Media Player\wmplayer.exe"
    media_file = os.path.abspath(os.path.relpath("assets/audio.mp3"))
    p = subprocess.call([wmp, media_file])


    playsound("audio.mp3")
    #engine = pyttsx3.init()
    #engine.say(audioString)
    #engine.runAndWait()

img = cv2.imread("assets/ikea.jpg")
h, w, c = img.shape
relative_w = 1500
relative_h = int(relative_w / w * h)
img = cv2.resize(img, (relative_w, relative_h))
img_copy = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)

# perform edge detection, then perform a dilation + erosion to
# close gaps in between object edges
edged = cv2.Canny(gray, 100, 200)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

# find contours in the edge map
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# find contour with biggest area
largest_contour = None
for c in cnts:
    largest = 0
    area = cv2.contourArea(c)

    if area > largest:
        largest = area
        largest_contour = c

box = cv2.minAreaRect(largest_contour)
box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")

cv2.drawContours(img_copy, [box.astype("int")], -1, (0, 255, 0), 2)

box_frame = np.float32(box)
img_frame = np.float32([[0, relative_h], [0, 0], [relative_w, 0], [relative_w, relative_h]])

matrix = cv2.getPerspectiveTransform(box_frame, img_frame)
straight_img = cv2.warpPerspective(img, matrix, (relative_w, relative_h))


gray2 = cv2.cvtColor(straight_img, cv2.COLOR_BGR2GRAY)
adaptive_threshold = cv2.adaptiveThreshold(gray2, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
adaptive_threshold_inv = cv2.bitwise_not(adaptive_threshold)
median_blur = cv2.medianBlur(adaptive_threshold, 3)

img_rgb = cv2.cvtColor(median_blur, cv2.COLOR_GRAY2RGB)

hImg, wImg, _ = img_rgb.shape

boxes = pytesseract.image_to_data(img_rgb)
print(boxes)

#record sentences from detected texts
blocks = []
previous_x = 0
block = []
for i, b in enumerate(boxes.splitlines()):
    if i != 0:
        b = b.split()

        if len(b) == 12:
            x, y, w, h = (int(b[6]), int(b[7]), int(b[8]), int(b[9]))
            cv2.rectangle(straight_img, (x, y), (w + x, h + y), (0, 0, 255), 1)
            cv2.putText(straight_img, b[11], (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (50, 50, 255), 2)

            if abs(x - previous_x) > 300:
                blocks.append({'block': block, 'x': previous_x})
                block = []

            block.append(b[11])
            previous_x = x

blocks.append({'block': block, 'x': previous_x})
print(blocks)

block_length = len(blocks)

for i in range(0, block_length):

    for j in range(i+1, block_length):

        if abs(blocks[i]['x'] - blocks[j]['x']) < 300:
            removed = blocks.pop(j)
            blocks.insert(i + 1, removed)
            break

print(blocks)

#reorder sentences into graph
paragraph = ""
previous_x = 0

for i, b in enumerate(blocks):

    if abs(b['x'] - previous_x) < 300:
        paragraph = paragraph + " ".join(b['block']) + "\n"

    else:
        paragraph = paragraph + " ".join(b['block']) + " "

    previous_x = b['x']

print(paragraph)

cv2.imshow("picture", img_copy)
#cv2.imshow("canny edge", edged)
cv2.imshow("straight image", straight_img)
cv2.imshow("median blur", median_blur)

cv2.waitKey(0)

speak(paragraph)

------------------------------------
#logs
#detected words table
level   page_num        block_num       par_num line_num        word_num        left    top     width   height  conf    text
1       1       0       0       0       0       0       0       1500    1125    -1
2       1       1       0       0       0       180     997     576     24      -1
3       1       1       1       0       0       180     997     576     24      -1
4       1       1       1       1       0       180     997     576     24      -1
5       1       1       1       1       1       180     1009    28      12      85      SEE
5       1       1       1       1       2       215     1008    34      12      85      OUR
5       1       1       1       1       3       257     993     77      35      95      BIRTHDAY
5       1       1       1       1       4       345     993     59      35      91      OFFERS
5       1       1       1       1       5       424     1013    2       3       7       "
5       1       1       1       1       6       730     1000    26      11      5       ot
2       1       2       0       0       0       499     1006    433     52      -1
3       1       2       1       0       0       499     1006    433     52      -1
4       1       2       1       1       0       499     1006    433     29      -1
5       1       2       1       1       1       499     1012    40      23      30      THE
5       1       2       1       1       2       546     1012    62      20      96      PRICES
5       1       2       1       1       3       614     1019    21      12      91      IN
5       1       2       1       1       4       641     1018    42      12      91      THIS
5       1       2       1       1       5       690     1017    104     13      92      CATALOGUE
5       1       2       1       1       6       801     1016    36      12      92      CAN
5       1       2       1       1       7       843     1006    49      22      96      ONLY
5       1       2       1       1       8       898     1006    34      22      96      GET
4       1       2       1       2       0       506     1036    395     22      -1
5       1       2       1       2       1       506     1040    61      12      95      LOWER
5       1       2       1       2       2       574     1027    51      35      73      UNTIL
5       1       2       1       2       3       633     1027    39      35      73      JULY
5       1       2       1       2       4       681     1037    20      13      79      31
5       1       2       1       2       5       709     1037    49      15      79      2019,
5       1       2       1       2       6       765     1037    59      12      96      NEVER
5       1       2       1       2       7       830     1036    71      12      95      HIGHER
2       1       3       0       0       0       170     1022    204     47      -1
3       1       3       1       0       0       174     1022    200     43      -1
4       1       3       1       1       0       176     1022    190     20      -1
5       1       3       1       1       1       176     1028    19      12      71      AT
5       1       3       1       1       2       206     1015    28      34      71      THE
5       1       3       1       1       3       240     1025    69      15      93      BACK
5       1       3       1       1       4       291     1015    17      34      93      OF
5       1       3       1       1       5       316     1022    50      20      15      THE.
4       1       3       1       2       0       170     1041    204     28      -1
5       1       3       1       2       1       170     1041    100     28      94      CATALOGUE
5       1       3       1       2       2       349     1042    25      3       17      mo
2       1       4       0       0       0       0       0       1500    1125    -1
3       1       4       1       0       0       0       0       1500    1125    -1
4       1       4       1       1       0       0       0       1500    1125    -1
5       1       4       1       1       1       0       0       1500    1125    95

#sentence
[{'block': ['SEE', 'OUR', 'BIRTHDAY', 'OFFERS', '"'], 'x': 424}, {'block': ['ot', 'THE', 'PRICES', 'IN', 'THIS', 'CATALOGUE', 'CAN', 'ONLY', 'GET'], 'x': 898}, {'bloc
k': ['LOWER', 'UNTIL', 'JULY', '31', '2019,', 'NEVER', 'HIGHER'], 'x': 830}, {'block': ['AT', 'THE', 'BACK', 'OF', 'THE.', 'CATALOGUE', 'mo'], 'x': 349}]

#ordered sentence
[{'block': ['SEE', 'OUR', 'BIRTHDAY', 'OFFERS', '"'], 'x': 424}, {'block': ['AT', 'THE', 'BACK', 'OF', 'THE.', 'CATALOGUE', 'mo'], 'x': 349}, {'block': ['ot', 'THE',
'PRICES', 'IN', 'THIS', 'CATALOGUE', 'CAN', 'ONLY', 'GET'], 'x': 898}, {'block': ['LOWER', 'UNTIL', 'JULY', '31', '2019,', 'NEVER', 'HIGHER'], 'x': 830}]

#paragraph
SEE OUR BIRTHDAY OFFERS " AT THE BACK OF THE. CATALOGUE mo
ot THE PRICES IN THIS CATALOGUE CAN ONLY GET LOWER UNTIL JULY 31 2019, NEVER HIGHER

reference:
perspective transform

adaptive threshold

text to speech

Thursday, 15 April 2021

opencv 31 perspective transform


skewed image, contour bounding box is calculated after canny edge detection

canny edge detection, book contour is outlined

after perspective transform, book is straightened
#main.py
import cv2
import numpy as np
import imutils

high = 200
low = 100

trackbars_img = np.uint8(np.full((50, 500, 3), 255))
cv2.imshow('trackbars', trackbars_img)

def high_change(x):
    global high
    high = x

def low_change(x):
    global low
    low = x

cv2.createTrackbar('low', 'trackbars', 100, 150, low_change)
cv2.createTrackbar('high', 'trackbars', 200, 255, high_change)

while True:
    img = cv2.imread("assets/ikea.jpg")
    h, w, c = img.shape
    relative_h = int(1000/w*h)
    img = cv2.resize(img, (1000, relative_h))
    img_copy = img.copy()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)

    # perform edge detection, then perform a dilation + erosion to
    # close gaps in between object edges
    edged = cv2.Canny(gray, low, high)
    edged = cv2.dilate(edged, None, iterations=1)
    edged = cv2.erode(edged, None, iterations=1)

    # find contours in the edge map
    cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)

    # find contour with biggest area
    largest_contour = None
    for c in cnts:
        largest = 0
        area = cv2.contourArea(c)

        if area > largest:
            largest = area
            largest_contour = c

    box = cv2.minAreaRect(largest_contour)
    box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
    box = np.array(box, dtype="int")

    """
    box contains coordinates of 4 vertices 
    [[ 81 801]
     [ 95  24]
     [890  37]
     [877 815]]
    """

    cv2.drawContours(img_copy, [box.astype("int")], -1, (0, 255, 0), 2)

    #transform area of interest to cover entire image
    box_frame = np.float32(box)
    img_frame = np.float32([[0, relative_h], [0, 0], [1000, 0], [1000, relative_h]])

    matrix = cv2.getPerspectiveTransform(box_frame, img_frame)
    straight_img = cv2.warpPerspective(img_copy, matrix, (1000, relative_h))

    if cv2.waitKey(1) == ord('q'):
        break

    cv2.imshow("picture", img_copy)
    cv2.imshow("canny edge", edged)
    cv2.imshow("straight image", straight_img)

reference: