Esempio n. 1
0
def disprange_filter():
    if request.method == "POST":
        try:
            delete_images()
            image_src = 'static/uploads/img.png'
            im = Image.open(image_src)
            # Se calculeaza "distanta" dintre pixelelii mai mari ca pixelul median si pixelii mai mici ca pixelul median dintr-un bloc de pixeli 3x3
            im_disprange = Image.fromarray(
                np.uint8(
                    1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=5)),
                             dtype='float32') + 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=6)),
                             dtype='float32') + 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=7)),
                             dtype='float32') + 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=8)),
                             dtype='float32') - 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=0)),
                             dtype='float32') - 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=1)),
                             dtype='float32') - 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=2)),
                             dtype='float32') - 1 / 4 *
                    np.array(im.filter(ImageFilter.RankFilter(size=3, rank=3)),
                             dtype='float32')))
            im_disprange.save('static/uploads/img_disprange.png')
            image_url_disprange = url_for('static',
                                          filename="uploads/img_disprange.png")
            return jsonify({'image_url_disprange': image_url_disprange})
        except Exception as e:
            print(e)
Esempio n. 2
0
def __random_rank_blur(img):
    w, h = img.size[0], img.size[1]
    img = img.resize((2 * w, 2 * h))
    rank = np.random.randint(0, rank_blur_range * rank_blur_range)
    img = img.filter(ImageFilter.RankFilter(rank_blur_range, rank))
    img = img.resize((w, h))
    return img
Esempio n. 3
0
 def auto_rankfilter_exec(self):
     self.image = self.image.filter(
         ImageFilter.RankFilter(
             self.ops_vals["rankfilter"],
             int(self.ops_vals["rankfilter"] * self.ops_vals["rankfilter"] /
                 2)))
     self.loadImageFromPIX(self.image)
Esempio n. 4
0
    def call(self, img):

        if img is None: raise ValueError('img is None')

        im_n = img.copy()

        gauss_blur_low, gauss_blur_high = 0, self.gauss_blur
        blur_low, blur_high = gauss_blur_high, gauss_blur_high + self.blur
        smooth_low, smooth_high = blur_high, blur_high + self.smooth
        smooth_more_low, smooth_more_high = smooth_high, smooth_high + self.smooth_more
        rank_low, rank_high = smooth_more_high, smooth_more_high + self.rank_filter

        r = random()
        if gauss_blur_low <= r <= gauss_blur_high:
            im_n = im_n.filter(ImageFilter.GaussianBlur(1))
        elif blur_low < r <= blur_high:
            im_n = im_n.filter(ImageFilter.BLUR)
        elif smooth_low < r <= smooth_high:
            im_n = im_n.filter(ImageFilter.SMOOTH)
        elif smooth_more_low < r <= smooth_more_high:
            im_n = im_n.filter(ImageFilter.SMOOTH_MORE)
        elif rank_low < r <= rank_high:
            im_n = im_n.filter(ImageFilter.RankFilter(size=3, rank=7))
        else:
            pass
        return im_n
Esempio n. 5
0
    def features(self):
        """
        Calculate significant image features.

        This is done by:

        1. Finding the `channels` most prominent colors after filtering out
           values less than `min_color` or greater than `max_color`.
        2. Removing all other colors and converting the image to monochrome.
        3. Applying a rank filter to reduce noise.
        3. Separating the image into at most `max_chars` features, i.e. areas
           with at least `min_feature_pixels` number of contiguous pixels.

        Return:
            list: A least of monochrome `Image` objects representing
                significant features.
        """
        im = monochrome(self.im,
                        limit=self.channels,
                        min=self.min_color,
                        max=self.max_color)

        if self.rank_size > 0:
            im = im.filter(
                ImageFilter.RankFilter(self.rank_size, self.rank_value))

        return features(im,
                        max_features=self.max_chars,
                        min_pixels=self.min_feature_pixels)
Esempio n. 6
0
def random_rank_blur(img, rank_blur_range):
    img = Image.fromarray(img)
    w, h = img.size[0], img.size[1]
    img = img.resize((2 * w, 2 * h))
    rank = np.random.randint(0, rank_blur_range * rank_blur_range)
    img = img.filter(ImageFilter.RankFilter(rank_blur_range, rank))
    img = img.resize((w, h))
    img = np.array(img)
    return img
Esempio n. 7
0
def filter(request, id_image):
    myObj = Photo.objects.get(pk=id_image)
    image_path = myObj.file.path
    img = Image.open(image_path)

    # applying the rank filter
    out = img.filter(ImageFilter.RankFilter(size=3, rank=3 * 3 - 1))
    out.save(image_path)

    return redirect('effects', id_image)
Esempio n. 8
0
def rnk(image, radius, rank=50, amount=100):
    """Apply a filter
    - amount: 0-1"""
    rank /= 100.0
    r = int((radius * radius - 1) * rank)
    image = imtools.convert_safe_mode(image)
    ranked = image.filter(ImageFilter.RankFilter(radius, r))
    if amount < 100:
        return imtools.blend(image, ranked, amount / 100)
    return ranked
Esempio n. 9
0
    def rank_filter(self,rank):
        '''
        用于rankfilter操作
        Args:

            rank:像素的次序

        '''
        self.resume()
        self.img = self.img.filter(ImageFilter.RankFilter(3,rank))
        self.update_image()
Esempio n. 10
0
def char_op(trg):
    trg = rem_back(trg)
    trg = rem_back_rev(trg)
    cnt = ImageEnhance.Contrast(trg)
    trg = cnt.enhance(2)
    trg = trg.filter(ImageFilter.MedianFilter(9))
    trg = trg.filter(ImageFilter.RankFilter(5, 3))
    br = ImageEnhance.Brightness(trg)
    trg = br.enhance(1)
    trg = trg.convert("RGB")
    trg = ImageOps.expand(trg, 30, 'white')
    return trg
Esempio n. 11
0
def generate_map(size, kernelsize, numiterations):
    im = Image.new('RGB', (size, size), color=IMPASSABLE)

    # init with random data
    for x in range(0, im.width):
        for y in range(0, im.height):
            im.putpixel((x, y), random.choice([IMPASSABLE, PASSABLE]))

    # apply filter multiple times
    for i in range(numiterations):
        im = im.filter(ImageFilter.RankFilter(kernelsize, kernelsize**2 // 2))

    return im
Esempio n. 12
0
def augment(image):

    random_transform = random.randint(-1, 4)
    if random_transform == 0:
        image = image.rotate(random.randint(-5, 5))
    if random_transform == 1:
        image = image.filter(ImageFilter.GaussianBlur(radius=1))
    if random_transform == 2:
        image = image.filter(ImageFilter.RankFilter(size=3, rank=1))
    if random_transform == 3:
        image = image.filter(ImageFilter.MedianFilter(size=3))
    if random_transform == 4:
        image = image.filter(ImageFilter.MaxFilter(size=3))
    return image
Esempio n. 13
0
def getcode(image):
    threshold = 69
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    image = Image.open(image).convert('L')
    image = image.resize((216, 81))
    image = image.filter(ImageFilter.RankFilter(5, 13))
    image = image.point(table, '1')
    image.show()

    code = pytesseract.image_to_string(image, config='--psm letters')
    return code
Esempio n. 14
0
def modifyfunction():
    # temp = Image.open("display.jpg")
    playList = [
        ImageFilter.CONTOUR, ImageFilter.EMBOSS, ImageFilter.EDGE_ENHANCE_MORE,
        ImageFilter.BLUR, ImageFilter.DETAIL, ImageFilter.FIND_EDGES,
        ImageFilter.EDGE_ENHANCE, ImageFilter.SMOOTH_MORE, ImageFilter.SMOOTH,
        ImageFilter.SHARPEN,
        ImageFilter.RankFilter(5, 0),
        ImageFilter.MaxFilter(3),
        ImageFilter.MinFilter(3)
    ]

    for i in playList:
        temp = Image.open("display.jpg")
        new_img = temp.filter(i)
        new_img.show()
Esempio n. 15
0
    def predict(self, img):
        # img = np.array(img.convert('L'))

        img = img.convert('L')  # Gray scale
        ne_img = ImageEnhance.Contrast(img).enhance(2)
        ers_img = ne_img.filter(ImageFilter.RankFilter(3, 1))

        res_img = ers_img.resize((res_width, res_height * 3), Image.ANTIALIAS)
        img = res_img

        # We divide the test image in 3
        # We could also try to test with the testing set of 1 character images
        width, height = img.size
        area = (0, height / 3, width, height - height / 3)
        img2 = (img.crop(area))
        area = (0, (height / 3) * 2, width, height)
        img3 = (img.crop(area))
        area = (0, 0, width, height / 3)
        img = (img.crop(area))

        img = np.array(img)
        img2 = np.array(img2)
        img3 = np.array(img3)

        feat = np.resize(img, tam_feature_vec)  # feature vector
        feat2 = np.resize(img2, tam_feature_vec)  # feature vector
        feat3 = np.resize(img3, tam_feature_vec)  # feature vector

        # d1 = np.linalg.norm(self.model - feat, axis=1)  # measure distance --- Frobenius Norm / Euclidean norm
        dist = (np.sqrt(np.cumsum(np.square(self.model - feat), axis=1)))[:,
                                                                          -1]

        # d2 = np.linalg.norm(self.model - feat2, axis=1)  # measure distance --- Frobenius Norm / Euclidean norm
        dist2 = (np.sqrt(np.cumsum(np.square(self.model - feat2), axis=1)))[:,
                                                                            -1]

        # d3 = np.linalg.norm(self.model - feat3, axis=1)  # measure distance --- Frobenius Norm / Euclidean norm
        dist3 = (np.sqrt(np.cumsum(np.square(self.model - feat3), axis=1)))[:,
                                                                            -1]

        y_pred = self.y_train[np.argmin(dist)]  # Get the closest
        y_pred2 = self.y_train[np.argmin(dist2)]  # Get the closest
        y_pred3 = self.y_train[np.argmin(dist3)]  # Get the closest

        final_pred = [y_pred, y_pred2, y_pred3]

        return final_pred
Esempio n. 16
0
    def predict(self, img):
        # img = np.array(img.convert('L'))

        img = img.convert('L')  # Gray scale
        ne_img = ImageEnhance.Contrast(img).enhance(2)
        ers_img = ne_img.filter(ImageFilter.RankFilter(3, 1))
        img = np.array(ers_img)

        feat = np.resize(img, tam_feature_vec)  # feature vector

        dist = np.linalg.norm(
            self.model - feat,
            axis=1)  # measure distance --- Frobenius Norm / Euclidean norm
        # dist = (np.sum(np.abs(self.model - feat) ** 2, axis=-1) ** (1. / 2))         SLOWER

        y_pred = self.y_train[np.argmin(dist)]  # Get the closest
        return y_pred
Esempio n. 17
0
def loadData(filePath):
    f = open(filePath, 'rb')
    data = []
    img = image.open(f)

    img = img.filter(ImageFilter.RankFilter(3, 8))

    m, n = img.size
    print(m, n)
    for i in range(m):
        for j in range(n):
            # RGB 0-1
            x, y, z = img.getpixel((i, j))
            # color in data
            data.append([x / 256.0, y / 256.0, z / 256.0])
    f.close()
    return log_pic(np.mat(data), 10), m, n
Esempio n. 18
0
 def rank_filter(self):
     image = Image.open(self.name)
     # print("Params: ", self.container.rwindow.mask)
     try:
         subwindow = RgbImageWindow(
             self.name, 0, self.container,
             image.filter(
                 ImageFilter.RankFilter(
                     size=self.container.rwindow.filter_size,
                     rank=self.container.rwindow.filter_rank)))
         subwindow.update_pixmap(subwindow.image)
         if not subwindow:
             QMessageBox.information(self.container, "Error",
                                     "Fail to create a sub window")
         else:
             self.container.mdiArea.addSubWindow(subwindow)
             subwindow.show()
     except Exception:
         QMessageBox.information(self.container, "Error", "Parameter error")
def outlineMarks(image, imageWidth, imageHeight):
    def colorsAreVeryDifferent(color1, color2):
        r1, g1, b1 = color1[0], color1[1], color1[2]
        r2, g2, b2 = color2[0], color2[1], color2[2]
        if (r1 - r2 > 15 or g1 - g2 > 15 or b1 - b2 > 15):
            return True
        return False

    image = image.resize((imageWidth, imageHeight), Image.BICUBIC)
    maxPass = image.filter(ImageFilter.RankFilter(13, 99))  #radius 13
    for x in range(image.size[0]):
        for y in range(image.size[1]):
            currentColor = image.getpixel((x, y))
            maxPassColor = maxPass.getpixel((x, y))
            #Compare current pixel with locally brightest thing
            if (colorsAreVeryDifferent(maxPassColor, currentColor)):
                image.putpixel((x, y), (0, 255, 0))  #make pixel very green
            else:
                image.putpixel((x, y), (255, 255, 255))
    return image
Esempio n. 20
0
 def __init__(self, archivo):
     self.archivo = archivo
     self.img = Image.open(archivo)
     size = self.img.size
     # print(self.img.size)
     tam = 1600
     self.img = self.img.resize(
         (tam, int(size[1] * tam /
                   size[0]))) if size[0] > size[1] else self.img.resize(
                       (int(size[0] * tam / size[1]), tam))
     # self.img = self.img.filter(ImageFilter.UnsharpMask(6,80))
     # self.img = self.img.filter(ImageFilter.GaussianBlur())
     # self.img = self.img.filter(ImageFilter.UnsharpMask(4))
     tamfilter = 3
     self.img = self.img.filter(
         ImageFilter.RankFilter(tamfilter, int(tamfilter * tamfilter / 2)))
     # self.img = ImageOps.equalize(self.img)
     # self.img = ImageOps.autocontrast(self.img)
     # print(self.img.size)
     self.regiones = []
Esempio n. 21
0
def alphaqsr_filter():
    if request.method == "POST":
        try:
            delete_images()
            image_src = 'static/uploads/img.png'
            im = Image.open(image_src)
            alpha = int(request.get_data())
            imgname = 'img_alphaqsr_' + str(alpha) + '.png'
            if alpha == 1:
                # Se calculeaza "distanta" 2 pixeli din capatul vectorului minus alpha dintr-un bloc de pixeli 3x3
                im_alphaqsr = Image.fromarray(
                    np.uint8(
                        np.array(
                            im.filter(ImageFilter.RankFilter(size=3, rank=7)))
                        - np.array(
                            im.filter(ImageFilter.RankFilter(size=3, rank=1))))
                )
                im_alphaqsr.save('static/uploads/' + imgname)
                image_url_alphaqsr = url_for('static',
                                             filename="uploads/" + imgname)
                return jsonify({'image_url_alphaqsr': image_url_alphaqsr})
            elif alpha == 2:
                im_alphaqsr = Image.fromarray(
                    np.uint8(
                        np.array(
                            im.filter(ImageFilter.RankFilter(size=3, rank=6)))
                        - np.array(
                            im.filter(ImageFilter.RankFilter(size=3, rank=2))))
                )
                im_alphaqsr.save('static/uploads/' + imgname)
                image_url_alphaqsr = url_for('static',
                                             filename="uploads/" + imgname)
                return jsonify({'image_url_alphaqsr': image_url_alphaqsr})
            elif alpha == 3:
                im_alphaqsr = Image.fromarray(
                    np.uint8(
                        np.array(
                            im.filter(ImageFilter.RankFilter(size=3, rank=5)))
                        - np.array(
                            im.filter(ImageFilter.RankFilter(size=3, rank=3))))
                )
                im_alphaqsr.save('static/uploads/' + imgname)
                image_url_alphaqsr = url_for('static',
                                             filename="uploads/" + imgname)
                return jsonify({'image_url_alphaqsr': image_url_alphaqsr})
        except Exception as e:
            print(e)
Esempio n. 22
0
    def build_model(self, traindata):
        # Initialization
        num_train = len(traindata)
        print(num_train)
        model = np.zeros((num_train, tam_feature_vec))
        y_train = [['U+0000'] * 3 for i in range(num_train)]

        # Convert images to features
        for i in range(num_train):
            img, codes = traindata[i]  # Get an image and label

            # img = np.array(img.convert('L'))  # Gray scale
            img = img.convert('L')  # Gray scale
            ne_img = ImageEnhance.Contrast(img).enhance(2)
            ers_img = ne_img.filter(ImageFilter.RankFilter(3, 1))
            img = np.array(ers_img)

            # opencvImage = cv2.cvtColor(np.array(img),cv2.IMREAD_GRAYSCALE)
            # pxmin = np.min(opencvImage)
            # pxmax = np.max(opencvImage)
            # imgContrast = ((opencvImage - pxmin) / (pxmax - pxmin)) * 500
            # kernel = np.ones((3, 3), np.uint8)
            # imgMorph = cv2.erode(imgContrast, kernel, iterations=2)
            # # imgMorph = np.array(imgMorph, dtype=float)/float(255)
            # imgMorph = imgMorph.astype(np.uint)
            # cv2.imwrite('out2.png', imgMorph)
            # cv2.imshow('image', imgMorph)
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()

            # model[i,:] = np.resize(img,512)  # feature vector
            model[i, :] = np.resize(img, tam_feature_vec)

            y_train[i] = codes

        # Keep model and labels
        self.model = model
        self.y_train = y_train
def main():
    image = Image.open('../lenna.png')

    # Create a grayscale 3x3 sample image with values (0-9) * 28
    sample_image = Image.new('L', (3, 3))
    sample_image.putdata(list(map(lambda x: x * 28, range(9))))
    sample_image.resize((600, 600)).show('Sample image before ranking')

    # Apply 3x3 rank filters with ranks ranging 0-9
    for i in range(9):
        time.sleep(0.5)
        rank_filter = ImageFilter.RankFilter(3, rank=i)
        ranked_image = sample_image.filter(rank_filter)
        ranked_image.resize((600, 600)).show('Rank: %s, size 3x3' % i)

    # Now apply rank-based filters to the original image
    image.show('Original')

    for size in range(3, 9, 2):
        time.sleep(0.5)
        # Median filter, rank = (size * size) / 2 (the median value of
        # the sorted window). The median filter is used largely for
        # noise reduction.
        median_filter = ImageFilter.MedianFilter(size)
        median_filter_image = image.filter(median_filter)
        median_filter_image.show('Median filter, size: %sx%s' % (size, size))

        # Min filter, rank = 0 or the smallest pixel value in the sorted
        # window. Used in astrophotography. Dilates dark objects.
        min_filter = ImageFilter.MinFilter(size)
        min_filter_image = image.filter(min_filter)
        min_filter_image.show('Minimum filter, size: %sx%s' % (size, size))

        # Max filter, rank = size * size - 1 or the biggest pixel value
        # in the sorted window.
        max_filter = ImageFilter.MaxFilter(size)
        max_filter_image = image.filter(max_filter)
        max_filter_image.show('Maximum filter, size: %sx%s' % (size, size))
Esempio n. 24
0
                "SHARPEN",
                "RankFilter",
                "MaxFilter",
                "MinFilter",
                ]
playList_dict = {"CONTOUR": ImageFilter.CONTOUR,
                  "EMBOSS": ImageFilter.EMBOSS,
                  "EDGE_ENHANCE_MORE": ImageFilter.EDGE_ENHANCE_MORE,
                  "BLUR": ImageFilter.BLUR,
                  "DETAIL": ImageFilter.DETAIL,
                  "FIND_EDGES":ImageFilter.FIND_EDGES,
                  "EDGE_ENHANCE": ImageFilter.EDGE_ENHANCE,
                  "SMOOTH_MORE": ImageFilter.SMOOTH_MORE,
                  "SMOOTH": ImageFilter.SMOOTH,
                  "SHARPEN": ImageFilter.SHARPEN,
                  "RankFilter": ImageFilter.RankFilter(5,0),
                  "MaxFilter": ImageFilter.MaxFilter(3),
                  "MinFilter":  ImageFilter.MinFilter(3),
                }
def CurSelet(self):
    key = str((listbox.get(ACTIVE)))
    print(key)
    print(playList_dict[key])
    temp = Image.open("pic/display.jpg")
    new_img = temp.filter(playList_dict[key])
    new_img.save("new_img.jpg")
    outputFile = new_img.resize((1000,600),Image.ANTIALIAS)
    outputFile.save("pic/{}.jpg".format(key))


listbox = tk.Listbox(gui, background="Blue", fg="white",selectbackground="Red",highlightcolor="Red")
Esempio n. 25
0
def medfilt(pic=None, letter=None, level=7):
    pic = getpic(pic, letter)
    pic1 = pic.filter(ImageFilter.RankFilter(3, level))
    # pic1.show(title = "Rank filter applied")
    return pic1
Esempio n. 26
0
    def build_model(self, traindata):
        # Initialization
        num_train = len(traindata)
        print(num_train)

        model = np.zeros((num_train * 3, tam_feature_vec))

        # We can use this part to divide the three letter images and then feed them the same way as the one letter training set
        #   we create the pickle set using this part of the code
        #   Uncomment the parts of the code that you need
        # TAGS = ['U+3042', 'U+3044', 'U+3046', 'U+3048', 'U+304A', 'U+304B', 'U+304D', 'U+304F', 'U+3051', 'U+3053',
        #         'U+3055', 'U+3057', 'U+3059', 'U+305B', 'U+305D', 'U+305F', 'U+3061', 'U+3064', 'U+3066', 'U+3068',
        #         'U+306A', 'U+306B', 'U+306C', 'U+306D', 'U+306E', 'U+306F', 'U+3072', 'U+3075', 'U+3078', 'U+307B',
        #         'U+307E', 'U+307F', 'U+3080', 'U+3081', 'U+3082', 'U+3084', 'U+3086', 'U+3088', 'U+3089', 'U+308A',
        #         'U+308B', 'U+308C', 'U+308D', 'U+308F', 'U+3090', 'U+3091', 'U+3092', 'U+3093']
        # training_data = []

        y_train = [['U+0000'] for i in range(num_train * 3)]

        # Convert images to features
        for i in range(num_train):
            img, codes = traindata[i]  # Get an image and label

            # img = np.array(img.convert('L'))  # Gray scale
            img = img.convert('L')  # Gray scale

            ne_img = ImageEnhance.Contrast(img).enhance(2)
            ers_img = ne_img.filter(ImageFilter.RankFilter(3, 1))
            res_img = ers_img.resize((res_width, res_height * 3),
                                     Image.ANTIALIAS)
            img = res_img
            width, height = img.size
            area = (0, height / 3, width, height - height / 3)
            img2 = (img.crop(area))
            area = (0, (height / 3) * 2, width, height)
            img3 = (img.crop(area))
            area = (0, 0, width, height / 3)
            img = (img.crop(area))

            # img.show()
            # img2.show()
            # img3.show()

            img = np.array(img)
            img2 = np.array(img2)
            img3 = np.array(img3)

            ###########    If you need to create pickle
            # training_data.append([img,codes[0]])
            # training_data.append([img2, codes[1]])
            # training_data.append([img3, codes[2]])
            ###########

            # opencvImage = cv2.cvtColor(np.array(img),cv2.IMREAD_GRAYSCALE)
            # pxmin = np.min(opencvImage)
            # pxmax = np.max(opencvImage)
            # imgContrast = ((opencvImage - pxmin) / (pxmax - pxmin)) * 500
            #
            # kernel = np.ones((3, 3), np.uint8)
            # imgMorph = cv2.erode(imgContrast, kernel, iterations=2)
            # # imgMorph = np.array(imgMorph, dtype=float)/float(255)
            # imgMorph = imgMorph.astype(np.uint)
            # cv2.imwrite('out2.png', imgMorph)
            # cv2.imshow('image', imgMorph)
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()

            # model[i,:] = np.resize(img,512)  # feature vector

            model[i, :] = np.resize(img, tam_feature_vec)
            model[i + num_train, :] = np.resize(img2, tam_feature_vec)
            model[i + num_train * 2, :] = np.resize(img3, tam_feature_vec)

            #print(np.array(img).shape)
            #print(len(model[i,:]))
            #print(len(np.resize(img,512)))
            # print(codes)
            # print("meee"+codes[2])
            y_train[i] = codes[0]
            y_train[i + num_train] = codes[1]
            y_train[i + num_train * 2] = codes[2]

            if i % 1000 == 0:
                print("Training ", i)

            # break

        ########################################################################

        #In case you need to build the pickle data set
        # Shuffle the data just in case the words are ordered alphabetically
        # random.shuffle(training_data)
        #
        # X = []
        # y = []
        #
        # for features, label in training_data:
        #     X.append(features)
        #     y.append(label)
        #
        # X = np.array(X).reshape(-1, res_width, res_height, 1)
        #
        # pickle_out = open("X_THREE_2.pickle", "wb")
        # pickle.dump(X, pickle_out)
        # pickle_out.close()
        #
        # pickle_out = open("y_THREE_2.pickle", "wb")
        # pickle.dump(y, pickle_out)
        # pickle_out.close()

        ##########################################################################

        # Keep model and labels
        self.model = model
        self.y_train = y_train
Esempio n. 27
0
targets = AlconTargets(datapath, train_ratio=0.8)
testdata = AlconDataset(datapath,targets.test, isTrainVal=False)
N = len(testdata)
sheet = testdata.getSheet()  # Get initial sheet
res_width = 40
res_height = 50
model = tf.keras.models.load_model("3.0T-128-2-128-1.model")


for i in range(N):
    # Prediction
    img = testdata[i]  # Get data
    # img.show()
    img = img.convert('L')  # Gray scale
    ne_img = ImageEnhance.Contrast(img).enhance(2)
    ers_img = ne_img.filter(ImageFilter.RankFilter(3, 1))
    res_img = ers_img.resize((res_width, res_height * 3), Image.ANTIALIAS)
    img = res_img
    # img.show()
    width, height = img.size
    area = (0, height / 3, width, height - height / 3)
    img2 = (img.crop(area))
    area = (0, (height / 3) * 2, width, height)
    img3 = (img.crop(area))
    area = (0, 0, width, height / 3)
    img = (img.crop(area))

    img = (np.array(img)).reshape(-1, res_width, res_height, 1)
    img2 = (np.array(img2)).reshape(-1, res_width, res_height, 1)
    img3 = (np.array(img3)).reshape(-1, res_width, res_height, 1)
Esempio n. 28
0
def process_image_rankfilter(img_name):
    img = Image.open(pathlib.Path(img_name))
    img = img.filter(ImageFilter.RankFilter(size=9, rank=2))
    img.save(export_folder + "/RankFilter_" + format(Path(img_name).stem) +
             image_extension)
    print("RankFilter added successfully")
Esempio n. 29
0
            for i in f1:
                #print(os.path.join(r1))
                counter += 1
                label = TAGS.index(adding)
                # if counter==3256:
                n = os.path.join(r1, i)
                #img_array = cv2.imread(n, cv2.IMREAD_GRAYSCALE)
                # img_array = img_array
                # imgContrast = cv2.pow(img_array/255.0, 1.1)
                # img_array = imgContrast
                #

                img = Image.open(n)
                img = img.convert('L')  # Gray scale
                n_img = ImageEnhance.Contrast(img).enhance(1.5)
                img = n_img.filter(ImageFilter.RankFilter(3, 2))
                img = img.resize((NEW_WIDTH, NEW_HEIGTH), Image.ANTIALIAS)

                new_array = np.asanyarray(img)
                # kernel = np.ones((4, 4), np.uint8)
                #img_array = adjust_gamma(img_array, 0.5)
                # imgMorph = cv2.erode(imgContrast, kernel, iterations=1)
                # img_array = imgMorph

                #new_array = cv2.resize(img_array, (NEW_WIDTH, NEW_HEIGTH))
                training_data.append([new_array, label])

                # plt.imshow(img_array, cmap='gray')  # graph it
                # plt.show()
                # plt.imshow(imgContrast, cmap='gray')  # graph it
                # plt.show()
Esempio n. 30
0
    def test_rankfilter_properties(self):
        rankfilter = ImageFilter.RankFilter(1, 2)

        self.assertEqual(rankfilter.size, 1)
        self.assertEqual(rankfilter.rank, 2)