Example #1
0
def identify(image):

    mask_y = cv2.inRange(image, y_lower, y_upper)
    y = cv2.countNonZero(mask_y)

    mask_r = cv2.inRange(image, r_lower, r_upper)
    r = cv2.countNonZero(mask_r)

    print(y, r)

    if y > r:
        return "Banana"
    else:
        return "Apple"
Example #2
0
def sizeGrowth(image):

    # gray = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    gray8UC1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, thresh1 = cv2.threshold(gray8UC1, 95, 30, cv2.THRESH_BINARY)
    pixelCountValue = cv2.countNonZero(thresh1)
    contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_NONE)
    img = cv2.drawContours(image, contours, -1, (255, 255, 255), 1)
    gray8UC1_test = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret1, thresh12 = cv2.threshold(gray8UC1_test, 254, 255, cv2.THRESH_BINARY)
    pixelContourValue = cv2.countNonZero(thresh12)

    return pixelCountValue - pixelContourValue  #pixel value of filament
Example #3
0
def intensityFluores(image):

    #CV2 doesnt like some thing need to conver grey to 8UC1 format
    grey = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    #convert gray image to 8UC1 format
    gray8UC1 = cv2.cvtColor(grey, cv2.COLOR_BGR2GRAY)
    #cv2.imshow('Output gray', gray8UC1)
    #cv2.waitKey(0)

    #extract binary
    ret, thresh1 = cv2.threshold(gray8UC1, 30, 255, cv2.THRESH_BINARY)
    #Calculate the colored pixels to find the flourecence
    #Todo might need to change as dan doesnt like

    pixelCountValue = cv2.countNonZero(thresh1)

    #print(pixelCountValue)
    #cv2.imshow('Output thresh', thresh1)
    #cv2.waitKey(0)

    contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_NONE)
    img = cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)
    #cv2.imshow('Output', img)
    #cv2.waitKey(0)
    return pixelCountValue
Example #4
0
def pixel_difference(imgA: Image, imgB: Image, threshold: int = 0) -> float:
    height, width, _ = imgA.shape
    diffImg = cv2.absdiff(imgA, imgB)
    diffImg = cv2.cvtColor(diffImg, cv2.COLOR_BGR2GRAY)
    _, diffImg = cv2.threshold(diffImg, threshold, 255, cv2.THRESH_BINARY)
    numDiffPixels = cv2.countNonZero(diffImg)
    return numDiffPixels / (width * height)
Example #5
0
def identifyChunks(blobs, padding=2):
    contours, hierarchy = cv2.findContours(blobs.copy(), cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_SIMPLE)

    # create mask layer with black background
    mask = np.zeros(blobs.shape, np.uint8)

    for contour in range(len(contours)):
        (x, y, w, h) = cv2.boundingRect(contours[contour])

        # mask around bounding rectangle
        mask[y:y + h, x:x + w] = 0

        # white fill to bounding rectangle area
        cv2.drawContours(mask, contours, contour, (255, 255, 255), -1)

        # calculate ratio of non-black
        ratio = float(cv2.countNonZero(mask[y:y + h, x:x + w])) / (w * h)

        if ratio > 0.5 and w > 5 and h > 5:
            # cv2.rectangle(img, (x-padding, y-padding), (x+w+padding, y+h+padding), (0, 0, 255))
            textExtract(img[y - 3:y + h + 3, x - 3:x + w + 3])

    cv2.imwrite(path + "sample//result.jpg", img)

    return img
 def bar_percentage(cropped_image):
     white = [248, 248, 248]  # RGB
     diff = 30
     boundaries = [([white[2]-diff, white[1]-diff, white[0]-diff],
                 [white[2]+diff, white[1]+diff, white[0]+diff])]
     for (lower, _) in boundaries:
         lower = np.array(lower, dtype=np.uint8)
         upper = np.array([255, 255, 255], dtype=np.uint8)
         mask = cv2.inRange(cropped_image, lower, upper)
         ratio_white = cv2.countNonZero(mask)/(cropped_image.size/3)
         return(np.round(ratio_white*100, 2))
Example #7
0
    def get_gaze_ratio(self, lmk):
        eye_region = np.array([(lmk[0].x, lmk[0].y), (lmk[1].x, lmk[1].y),
                               (lmk[2].x, lmk[2].y), (lmk[3].x, lmk[3].y),
                               (lmk[4].x, lmk[4].y), (lmk[5].x, lmk[5].y)],
                              np.int32)
        # cv.polylines(frame, [eye_region], True, (0, 0, 255), 2)
        height, width, _ = self.frame.shape
        mask = np.zeros((height, width), np.uint8)
        cv.polylines(mask, [eye_region], True, 255, 2)
        cv.fillPoly(mask, [eye_region], 255)

        gray = cv.cvtColor(self.frame, cv.COLOR_BGR2GRAY)
        eye = cv.bitwise_and(gray, gray, mask=mask)

        min_x = max(0, np.min(eye_region[:, 0]))
        max_x = np.max(eye_region[:, 0])
        min_y = max(0, np.min(eye_region[:, 1]))
        max_y = np.max(eye_region[:, 1])

        gray_eye = eye[min_y:max_y, min_x:max_x]
        _, threshold_eye = cv.threshold(gray_eye, 40, 255, cv.THRESH_BINARY)
        h, w = threshold_eye.shape

        left_side_threshold = threshold_eye[0:h, 0:int(w / 2)]
        left_side_white = cv.countNonZero(left_side_threshold)

        right_side_threshold = threshold_eye[0:h, int(w / 2):w]
        right_side_white = cv.countNonZero(right_side_threshold)

        # print('left white:', left_side_white)
        # print('right white:', right_side_white)

        if left_side_white == 0 and right_side_white == 0:
            gaze_ratio = 1
        elif left_side_white == 0:
            gaze_ratio = 0.1
        elif right_side_white == 0:
            gaze_ratio = 10
        else:
            gaze_ratio = left_side_white / right_side_white
        return gaze_ratio
Example #8
0
def identifyChunks(imgPath,
                   blobs,
                   RECTpadding=2,
                   OCRpadding=3,
                   drawRect=True,
                   ocr=False):
    img = cv2.imread(imgPath)
    rect = img.copy()
    contours, _ = cv2.findContours(blobs.copy(), cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)

    # create mask layer with black background
    mask = np.zeros(blobs.shape, np.uint8)

    i = 0
    for contour in range(len(contours)):
        i = i + 1
        (x, y, w, h) = cv2.boundingRect(contours[contour])

        # mask around bounding rectangle
        mask[y:y + h, x:x + w] = 0

        # white fill to bounding rectangle area
        cv2.drawContours(mask, contours, contour, (255, 255, 255), -1)
        # cv2.imwrite(path+"sample//result" + str(i) + ".jpg",mask)

        # calculate ratio of non-black
        ratio = float(cv2.countNonZero(mask[y:y + h, x:x + w])) / (w * h)

        if w > 5 and h > 5:
            if (drawRect == True):
                cv2.rectangle(rect, (x - RECTpadding, y - RECTpadding),
                              (x + w + RECTpadding, y + h + RECTpadding),
                              (0, 0, 255), 2)

            if (ocr == True):
                while True:
                    try:
                        textExtract(
                            img[y - OCRpadding:y + h + OCRpadding,
                                x - OCRpadding:x + w + OCRpadding], i)
                        break
                    except:
                        OCRpadding = OCRpadding - 1

    cv2.imwrite(path + "itinerary//result.jpg", rect)

    return img
def _denoise_decrypted_image(img: np.ndarray) -> None:
    i: int = 0
    rows, cols = img.shape
    pixel_sum: int

    while i < rows:
        non_zero_count: int = cv2.countNonZero(img[i])
        if non_zero_count == int(cols / 2):
            img[i, 0:cols] = 0
        elif non_zero_count != cols:
            j: int = 0
            while j < cols:
                if img[i, j] != img[i, j + 1]:
                    img[i, j:j + 2] = 0
                j += 2
        i += 1
Example #10
0
def skeletize(img):
    size = np.size(img)
    skel = np.zeros(img.shape, np.uint8)
    element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
    done = False

    while not done:
        eroded = cv2.erode(img, element)
        temp = cv2.dilate(eroded, element)
        temp = cv2.subtract(img, temp)
        skel = cv2.bitwise_or(skel, temp)
        img = eroded.copy()

        zeroes = size - cv2.countNonZero(img)
        if zeroes == size:
            done = True

    return skel
Example #11
0
def cutlie_black(Path, Number, LiePath):
    Photo = cv.imdecode(np.fromfile(Path, dtype=np.uint8), cv.IMREAD_UNCHANGED)
    ErZhiImg = thresh_binary(Photo)
    row, col = ErZhiImg.shape
    listt = []
    for BlackTemp in range(col):
        listt.append((ErZhiImg[:, BlackTemp] < 250).sum())
        if listt[-1] < 10:
            listt[-1] = 0

    No1 = []
    No2 = []
    np_list = np.array(listt)  # 将列表list或元组tuple转换为 ndarray 数组

    if cv.countNonZero(ErZhiImg) < col * row / 1.5:  # 黑底子白字
        MaxValue = max(listt)
        MinValue = np.min(np_list[np.nonzero(np_list)])

        i = int(0)
        index = 0

        while i < col - 1:
            if MinValue + 20 < np_list[i] <= MaxValue:
                no1 = i
                for j in range(col)[i + 100:]:
                    if MaxValue - 60 < np_list[j]:
                        no2 = j + 20
                        no1 = i
                        if no2 - no1 > 200:
                            No1.append(no1)
                            No2.append(no2)
                            # roww, coll = ErZhiImg[:, int(No1[index]): int(No2[index])].shape
                            # if cv.countNonZero(ErZhiImg[:, int(No1[index]): int(No2[index])]) < coll * roww / 1.5:  # 黑底子白字
                            cv.imencode(
                                '.jpg',
                                Photo[:, int(No1[index]):int(No2[index])].copy(
                                ))[1].tofile(LiePath + Number + "-" +
                                             str(index + 1) + "lie.jpg")
                            index = index + 1
                            i = j
                            break
            i += 1
Example #12
0
                continue

            (grabbed, frame) = camera.read()
            frame = imutils.resize(frame, width=700)
            clone = frame.copy()

            (height, width) = frame.shape[:2]

            #potential speedup if converted to grayscale, the net should intake grayscale as well
            grayClone = cv2.cvtColor(clone, cv2.COLOR_BGR2GRAY)

            # Calculate absolute difference of current frame and
            # the next frame

            _diff = cv2.absdiff(grayClone, previous)
            num_diff = cv2.countNonZero(_diff)

            # Calculate the minimum nonzero pixels in order to update the background
            if min_diff is None:
                min_diff = np.min(num_diff)
                continue
            min_diff = np.min(
                num_diff) if min_diff > np.min(num_diff) else min_diff

            if num_diff > min_diff:
                # gives coordinates in (x,y) format. Note that, row = x and column = y.
                # mask = cv2.findNonZero(_diff)
                # rows = 79844; cols = 1
                # pix_mask[tuple(mask.T)] = 0

                #for i in range (0, num_rows):
Example #13
0
def _count_black_pixels(img: object):

    black_pixels = img.size - cv2.countNonZero(img)

    return black_pixels
from cv2 import cv2
import numpy as np

cap = cv2.VideoCapture(
    0)  # video capture source camera (Here webcam of laptop)
ret, frame = cap.read()  # return a single frame in variable `frame`
image = frame
cv2.imwrite('testimage.jpg', image)

#create numpy arrays for the boundaries of colors
lower = np.array([0, 0, 0], dtype="uint8")
upper = np.array([15, 15, 15], dtype="uint8")

#find colors in boundary and apply mask
mask = cv2.inRange(image, lower, upper)
colorpixels = cv2.countNonZero(mask)
print("The number of pixels in the mask are: ", colorpixels)
print("The number of pixels in the total image are: ", mask.size)
print(colorpixels / mask.size)
if (colorpixels / mask.size > .02):
    print("Thank you for wearing a mask")
else:
    print("You better put on a mask!")

output = cv2.bitwise_and(image, image, mask=mask)

#show the image
cv2.imwrite("mask.jpg", mask)
#cv2.imwrite("maskmask.jpg",np.hstack([image, output]))

cap.release()
Example #15
0
def qiege_hang(WenJianJiaPath):
    FilePath = WenJianJiaPath + "lie//"
    FileList = os.listdir(FilePath)
    Num = 0
    for lieTemp in range(len(FileList)):
        liePhotoPath = FilePath + FileList[lieTemp]
        Photo = cv.imdecode(np.fromfile(liePhotoPath, dtype=np.uint8),
                            cv.IMREAD_UNCHANGED)
        ErZhiImg = thresh_binary(Photo)
        listt = []
        row, col = ErZhiImg.shape

        for BlackTemp in range(row):
            listt.append((ErZhiImg[BlackTemp, :] < 250).sum())
            if listt[-1] < 10:
                listt[-1] = 0
        No1 = []
        No2 = []
        maxValue = max(listt)  # 数组中最大值
        np_list = np.array(listt)  # 将列表list或元组tuple转换为 ndarray 数组
        minValue = np.min(np_list[np.nonzero(np_list)])

        i = int(0)
        index = 0
        while i < row - 1:
            # i = int(i)
            if minValue + 10 < np_list[i] < maxValue:
                no1 = i
                for j in range(row)[i + 100:]:
                    if maxValue - 10 < np_list[j]:
                        derta = j
                        NextHang = []
                        if derta > row - 21:
                            derta = row - 21
                        for derta in range(derta + 20)[derta:]:
                            NextHang.append(np_list[derta])
                        Flag = Judge(NextHang, maxValue -
                                     5)  # 每一行黑色点数量大于Base,则Flag = True
                        if Flag:
                            no2 = j + 30
                            no1 = i - 0
                            No1.append(no1)
                            No2.append(no2)
                            roww, coll = ErZhiImg[
                                int(No1[index]):int(No2[index]), :].shape
                            if (cv.countNonZero(ErZhiImg[
                                    int(No1[index]):int(No2[index]), :]) /
                                (coll * roww)) < 0.035:
                                # 剔除全黑图片
                                i = j
                                index = index + 1
                                break
                            else:
                                cv.imencode(
                                    '.jpg',
                                    Photo[int(No1[index]):int(No2[index]), :].
                                    copy())[1].tofile(
                                        WenJianJiaPath + "hang//" + ''.join(
                                            re.findall(r'[\u4e00-\u9fa5]',
                                                       WenJianJiaPath)) + "-" +
                                        str(Num + 1) + ".jpg")
                                index = index + 1
                                Num = Num + 1
                                i = j
                                break
                        else:
                            break
            i += 1
Example #16
0
def cut_row(img, row_list):
    # 定点横着的坐标
    print(row_list)

    minlist = []
    # single_images_with_rect = []
    row, col = img.shape
    np_list = np.array(row_list)

    avg = row / (ImgRow)
    i = 0
    if cv.countNonZero(img) < col * row / 2:  # 黑底子白字
        a = max(row_list)
        while i < row:
            if i >= row - 20:
                if a - 5 < np_list[i] <= np_list[i + 1:row].min():
                    minlist.append(row)
                    break
                if i == row - 1:
                    minlist.append(i)
                    break
            elif a - 3 < np_list[i] <= np_list[i:i + 15].min():
                if len(minlist) == 0:
                    minlist.append(i)
                else:
                    x = 0
                    y = 1
                    while np_list[i + x] >= a - 3 and i + x < row - 10:
                        x += 5
                    while np_list[i - y] >= a - 3:
                        y += 1
                    minlist.append(i + x / 2 - y / 2)
                i += 100
            i += 1
            i = int(i)
    else:
        a = min(row_list)
        while i < row:
            aa = np_list[i]
            if i >= row - 20:
                if a + 5 < np_list[i] <= np_list[i + 1:row].min():
                    minlist.append(row)
                    break
                if i == row - 1:
                    minlist.append(i)
                    break
            elif a + 3 < np_list[i] <= np_list[i:i + 15].min():
                if len(minlist) == 0:
                    minlist.append(i)
                else:
                    x = 0
                    y = 1
                    while np_list[i + x] <= a + 3 and i + x < row - 10:
                        x += 5
                    while np_list[i - y] <= a + 3:
                        y += 3
                    minlist.append(i + x / 2 - y / 2)
                i += avg
            i += 1
            i = int(i)

    if row - minlist[-1] > 0.4 * avg:
        minlist.append(row)
    # print(minlist)

    return minlist, col
Example #17
0
print("Press Ctrl-C to stop")
while (1):
    path = ''
    with mss.mss() as sct:
        monitor = {"top": 200, "left": 300, "width": 750, "height": 500}
        output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor)
        sct_img = sct.grab(monitor)

        mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
        path = output
    src = cv2.imread(path)
    hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)

    lower_white = np.array([0, 0, 152])
    upper_white = np.array([180, 79, 255])

    mask = cv2.inRange(hsv, lower_white, upper_white)
    print(cv2.countNonZero(mask))

    if (cv2.countNonZero(mask) < THRESHOLD or measure_time(timePassed)):
        timePassed = time.time()
        fish()

    print("this is the timer: " + str(time.time()))
    print("this is the time passed: " + str(timePassed))

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
Example #18
0
def cut_col(img, l):
    minlist = []
    np_list = np.array(l)

    row, col = img.shape
    avg = col / (imgcol + 1)
    if (cv.countNonZero(img) < col * row / 2):  #黑底子白字
        a = max(l)
        i = 20
        while i < col - 1:
            if i >= col - 11:
                if np_list[i] > a - 10 and np_list[i] <= np_list[i +
                                                                 1:col].min():
                    minlist.append(i)
                    break
                if i == col - 1:
                    minlist.append(i)
                    break
            else:
                if np_list[i] > a - 10 and np_list[i] <= np_list[i:i +
                                                                 5].min():
                    if len(minlist) == 0:
                        minlist.append(i)
                    else:
                        x = 0
                        y = 1
                        while i + x < col - 10 and np_list[i + x] >= a - 10:
                            x += 3
                        while np_list[i - y] >= a - 10:
                            y += 1
                        minlist.append(i + x / 2 - y / 2)
                    i += avg
            i += 1
        return (minlist, row)
    else:  #白底黑字
        i = 20
        a = min(l)
        while i < col - 1:
            if i >= col - 11:
                if np_list[i] < a + 10 and np_list[i] <= np_list[i +
                                                                 1:col].min():
                    minlist.append(i)
                    break
                if i == col - 1:
                    minlist.append(i)
                    break
            else:
                if np_list[i] < a + 10 and np_list[i] <= np_list[i:i +
                                                                 5].min():
                    if len(minlist) == 0:
                        minlist.append(i)
                    else:
                        x = 0
                        y = 1
                        while i + x < col - 10 and np_list[i + x] <= a + 10:
                            x += 3
                        while np_list[i - y] <= a + 10:
                            y += 1
                        minlist.append(i + x / 2 - y / 2)
                    i += avg
            i += 1
        return (minlist, row)
    thresh = 16
    cam = cv.VideoCapture(0)
    cam.set(cv.CAP_PROP_FRAME_WIDTH, 320)
    cam.set(cv.CAP_PROP_FRAME_HEIGHT, 240)
    if cam.isOpened() == False:
        print("Cam isn't opened")
        exit()
    i = [None, None, None]
    for n in range(3):
        i[n] = motion_picv.getGrayCameraImage(cam)
    flag = False
    checkFlag = 0
    while True:
        diff = motion_picv.diffImage(i)
        ret,thrimg=cv.threshold(diff, thresh, 1, cv.THRESH_BINARY)
        count = cv.countNonZero(thrimg)
        # if invader is checked
        if (count > 1):
            checkFlag += 1
        if checkFlag >= 10 and flag == False:
#             sendmail(i[2])
            flag = True
            print ("Invader is coming!")
        elif count == 0 and flag == True:
            flag = False
            checkFlag = 0

        # process next image
        motion_picv.updateCameraImage(cam, i)

        key = cv.waitKey(10)
Example #20
0
show = cv2.drawContours(org1.copy(), cnts, -1, (0, 255, 0), 1)
if show_process:
    imshow(show)

#对多个轮廓按照从上到下的顺序排序
cnts = sorted(cnts, key=lambda x: x[0][0][1])

rows = int(len(cnts) / 5)

TAB = ['A', 'B', 'C', 'D', 'E']
ANS = []

#检查每一行(即每一题)的答案
for i in range(rows):
    subcnts = cnts[i * 5:(i + 1) * 5]
    subcnts = sorted(subcnts, key=lambda x: x[0][0][0])

    total = []

    for (j, cnt) in enumerate(subcnts):
        mask = np.zeros(paper1.shape, dtype=np.uint8)
        cv2.drawContours(mask, [cnt], -1, 255, -1)  #-1表示填充

        mask = cv2.bitwise_and(paper1, paper1, mask=mask)
        total.append(cv2.countNonZero(mask))

    idx = np.argmax(np.array(total))
    ANS.append(TAB[idx])

print(ANS)
Example #21
0
# conts, _ = cv2.findContours(inv_warp.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(thresh_warp,conts,-1,(0,255,0),3)
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
height_fin, width_fin = warped.shape
height_cut = int(height_fin / 9)
width_cut = int(width_fin / 9)
labels = []
centers = []
for i in range(0, 9):
    for j in range(0, 9):
        crop = warped[i * height_cut:(i + 1) * height_cut,
                      j * width_cut:(j + 1) * width_cut]
        digit = cv2.resize(crop, (28, 28))
        _, digit2 = cv2.threshold(digit, 80, 255, cv2.THRESH_BINARY_INV)
        digit3 = clear_border(digit2)
        numpixel = cv2.countNonZero(digit3)
        _, digit4 = cv2.threshold(digit3, 0, 255, cv2.THRESH_BINARY_INV)
        if numpixel < 3:
            label = 0
        else:
            _, digit4 = cv2.threshold(digit4, 0, 255, cv2.THRESH_BINARY_INV)
            digit4 = digit4 / 255.0
            array = model.predict(digit4.reshape(1, 28, 28, 1))
            label = np.argmax(array)
        labels.append(label)
        centers.append((i * height_cut / 2, j * width_cut / 2))
        # print(label)
        # cv2.imshow("a", digit4)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
Example #22
0
 if maxValue - 20 < np_list[j]:
     derta = j
     NextHang = []
     if derta > row - 21:
         derta = row - 21
     for derta in range(derta + 20)[derta:]:
             NextHang.append(np_list[derta])
     Flag = Judge(NextHang, maxValue - 5) # 每一行黑色点数量大于Base,则Flag = True
     if Flag:
         no2 = j + 30
         no1 = i - 0
         No1.append(no1)
         No2.append(no2)
         hangPhotoPath = "E://Project//TestPy//hang//"
         roww, coll = ErZhiImg[int(No1[index]): int(No2[index]), :].shape
         if (cv.countNonZero(ErZhiImg[int(No1[index]): int(No2[index]), :]) / (coll * roww)) < 0.035:
             i = j
             index = index + 1
             break
         else:
             cv.imencode('.jpg', Photo[int(No1[index]): int(No2[index]), :].copy())[1].tofile(
                 hangPhotoPath + ''.join(re.findall(r'[\u4e00-\u9fa5]', liePhotoPath)) + "-" + str(
                     index + 1) + "-" + str(no1) + "-" + str(no2) + "hang.jpg")
             # re.findall(r'[\u4e00-\u9fa5]', liePhotoPath)
             index = index + 1
             print(hangPhotoPath + str(lieTemp) + "-" + str(index + 1) + "-" + str(no1) + "-" + str(
                 no2) + "hang.jpg")
             i = j
             break
     else:
         break
Example #23
0
from matplotlib import pyplot as plt
import numpy as np
from cv2 import cv2
upper = np.array([100, 120, 200], dtype="uint8")
lower = np.array([30, 70, 130], dtype="uint8")
cam = cv2.VideoCapture(0)
while True:
    ret, frame = cam.read()
    if ret:
        mask = cv2.inRange(frame, lower, upper)
        print(cv2.countNonZero(mask))
        output = cv2.bitwise_and(frame, frame, mask=mask)
        output = cv2.putText(output, str(cv2.countNonZero(mask)), (50, 50),
                             cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0))
        cv2.imshow("frame", np.hstack([frame, output]))
    if cv2.waitKey(delay=20) & 0xFF == ord('q'):
        break
s, image = cam.read()
cam.release()

print(s)
# image = cv2.imread('/Users/samuel.heavner/Downloads/finn-and-nico.jpeg')
# image = cv2.resize(image, (720, 1280))
# image = cv2.blur(image, (10, 10))
# print(image) # reads the image
# image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to HSV
figure_size = 9  # the dimension of the x and y axis of the kernal.
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask=mask)
cv2.imshow("images", np.hstack([image, output]))
cv2.waitKey(0)
Example #24
0
def cut_col(img, l, filename):
    minlistt = []
    No1 = []
    No2 = []
    np_list = np.array(l)  # 将列表list或元组tuple转换为 ndarray 数组

    row, col = img.shape
    avg = col / (ImgCol + 1)
    if cv.countNonZero(img) < col * row / 1.5:  # 黑底子白字
        a = max(l)
        minval = np.min(np_list[np.nonzero(np_list)])

        # print(minval)
        i = 10
        index = 0

        while i < col - 11:
            if i >= col - 11:
                i = int(i)
                if minval < np_list[i] <= np_list[i + 1:col].min():
                    minlistt.append(i)
                    break
                if i == col - 1:
                    minlistt.append(i)
                    break
            else:
                i = int(i)
                if minval < np_list[i] <= a:
                    # if minval < np_list[i] <= np_list[i:i + 5].min():
                    no1 = i
                    for j in range(col)[i + 100:]:
                        if a - 1 < np_list[j]:

                            no2 = j + 10
                            print(no1, no2)
                            if no2 - no1 > 200:
                                No1.append(no1)
                                No2.append(no2)
                                print(filename)
                                cv.imwrite(
                                    "E://Project//TestPy//ShufaTiqu//liu//liuLR//qiege//"
                                    + filename + "-" + str(j) + "~" + str(i) +
                                    "-" + "lie.jpg",
                                    img[:,
                                        int(No1[index]):int(No2[index])].copy(
                                        ))
                                index = index + 1
                                i = no2
                                break
            i += 1
        return minlistt, row
    else:  # 白底黑字
        i = 20
        a = min(l)
        while i < col - 1:
            if i >= col - 11:
                if np_list[i] < a + 10 and np_list[i] <= np_list[i +
                                                                 1:col].min():
                    minlistt.append(i)
                    break
                if i == col - 1:
                    minlistt.append(i)
                    break
            else:
                i = int(i)
                if a + 5 < np_list[i] <= np_list[i:i + 5].min():
                    if len(minlistt) == 0:
                        minlistt.append(i)
                    else:
                        x = 0
                        y = 1
                        while i + x < col - 10 and np_list[i + x] <= a + 10:
                            x += 3
                        while np_list[i - y] <= a + 10:
                            y += 1
                        minlistt.append(i + x / 2 - y / 2)
                    i += avg
            i += 1
        return minlistt, row
        # allocate memory for the mask which will contain the
        # rectangular bounding box of the stitched image region
        mask = np.zeros(thresh.shape, dtype="uint8")
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1)

        # create two copies of the mask: one to serve as our actual
        # minimum rectangular region and another to serve as a counter
        # for how many pixels need to be removed to form the minimum
        # rectangular region
        minRect = mask.copy()
        sub = mask.copy()

        # keep looping until there are no non-zero pixels left in the
        # subtracted image
        while cv2.countNonZero(sub) > 0:
            # erode the minimum rectangular mask and then subtract
            # the thresholded image from the minimum rectangular mask
            # so we can count if there are any non-zero pixels left
            minRect = cv2.erode(minRect, None)
            sub = cv2.subtract(minRect, thresh)

        # find contours in the minimum rectangular mask and then
        # extract the bounding box (x, y)-coordinates
        cnts = cv2.findContours(minRect.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        c = max(cnts, key=cv2.contourArea)
        (x, y, w, h) = cv2.boundingRect(c)

        # use the bounding box coordinates to extract the our final
Example #26
0
    segments = [
        ((0, 0), (w, dH)),  # top
        ((0, 0), (dW, h // 2)),  # top-left
        ((w - dW, 0), (w, h // 2)),  # top-right
        ((0, (h // 2) - dHC), (w, (h // 2) + dHC)),  # center
        ((0, h // 2), (dW, h)),  # bottom-left
        ((w - dW, h // 2), (w, h)),  # bottom-right
        ((0, h - dH), (w, h))  # bottom
    ]
    on = [0] * len(segments)

    #在段上循环,遍历每个线段的(x,y)坐标
    for (i, ((xA, yA), (xB, yB))) in enumerate(segments):
        #提取段ROI
        segROI = roi[yA:yB, xA:xB]
        total = cv2.countNonZero(segROI)
        area = (xB - xA) * (yB - yA)

        if total / float(area) > 0.5:
            on[i] = 1

    digit = DIGITS_LOOKUP[tuple(on)]
    digits.append(digit)
    cv2.rectangle(output, (x, y), (x + w, y + h), (0, 255, 0), 1)
    cv2.putText(output, str(digit), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (0, 255, 0), 2)

#将数字打印到屏幕并显示图像
print(u"{}{}.{} \u00b0c".format(*digits))
cv2.imshow("Input", image)
cv2.imshow("Output", output)