示例#1
0
文件: keywords.py 项目: kroman0/abc
def compare_screenshot_to_base(baseline, diff=100):
    """Calculate the exact difference between two images.

    :param string baseline: [required] base screenshot to compare
    :param int diff: value of maximum difference

    Example::

        Compare screenshot to base  base_screenshot.jpg

    """
    path = _get_screenshot()

    current_browser = _get_browser()

    if hasattr(current_browser, 'get_screenshot_as_file'):
        current_browser.get_screenshot_as_file(path)
    else:
        current_browser.save_screenshot(path)

    img1 = Iopen(path)
    img2 = Iopen(baseline)
    his1 = img1.histogram()
    his2 = img2.histogram()
    sqrtdiff = lambda a, b: (a - b) ** 2
    rms = sqrt(reduce(add, imap(sqrtdiff, his1, his2)) / len(his1))
    logger.info("RMS diff: %s" % rms)
    if rms > 0:
        idiff = difference(img1, img2)
        path = path.replace(".png", ".jpg")
        idiff.save(path)
        logger.info("diff image: %s" % path)
    if rms > diff:
        raise AssertionError(
            "Image: %s is different from baseline: %s" % (path, baseline))
示例#2
0
 def show(self, flag='image'):
     (_, name) = os.path.split(self.image_list[self.current_image_mark])
     if flag == 'image':
         path = self.path_image
         plotwindow = self.image
     elif flag == 'GT':
         path = self.path_mask_GT
         plotwindow = self.mask_GT
     elif flag == 'pred':
         path = self.path_mask_pred
         plotwindow = self.mask_pred
     try:
         img = Iopen(os.path.join(path, name))
         self.data[flag] = array(img)
         if (flag == 'GT' and self.data['pred'] is not None) or (
                 flag == 'pred' and self.data['GT'] is not None):
             matrix = evaluate.Matrix(self.data['pred'], self.data['GT'])
             _, miou = matrix.miou()
             _, acc = matrix.accuracy()
             kappa = matrix.kappa()
             self.miou.setText(f'{miou}')
             self.accuracy.setText(f'{acc}')
             self.kappa.setText(f'{kappa}')
         self.progressBar.setValue(self.current_image_mark + 1)
         img = img.resize((341, 251))
         self.file_path.setText(self.image_list[self.current_image_mark])
         plotwindow.setPixmap(img.toqpixmap())
         self.check_LastAndNext()
     except FileNotFoundError as e:
         raise (e)
示例#3
0
def compare_screenshot_to_base(baseline, diff=100):
    """Calculate the exact difference between two images.

    :param string baseline: [required] base screenshot to compare
    :param int diff: value of maximum difference

    Example::

        Compare screenshot to base  base_screenshot.jpg

    """
    path = _get_screenshot()

    current_browser = _get_browser()

    if hasattr(current_browser, 'get_screenshot_as_file'):
        current_browser.get_screenshot_as_file(path)
    else:
        current_browser.save_screenshot(path)

    img1 = Iopen(path)
    img2 = Iopen(baseline)
    his1 = img1.histogram()
    his2 = img2.histogram()
    sqrtdiff = lambda a, b: (a - b)**2
    rms = sqrt(reduce(add, imap(sqrtdiff, his1, his2)) / len(his1))
    logger.info("RMS diff: %s" % rms)
    if rms > 0:
        idiff = difference(img1, img2)
        path = path.replace(".png", ".jpg")
        idiff.save(path)
        logger.info("diff image: %s" % path)
    if rms > diff:
        raise AssertionError("Image: %s is different from baseline: %s" %
                             (path, baseline))
示例#4
0
def plot_eye_scatter(data: DataFrame, ax_in: Axes,
                     size: (int, int) = (35, 27)) -> list:
    """Standard formatted plot with eye ward symbol scatter.

    Arguments:
        data {DataFrame} -- Table with xCoordinate, yCoordinate, time,
         smoke and Name
        ax_in {Axes} -- Target axes for plot

    Keyword Arguments:
        size {[type]} -- Image size (default: {(14, 34)})

    Returns:
        list -- Returns list of generated plot entities.
    """
    # Map
    plot_map(ax_in)

    # Add labels
    #data = label_smoke_name_time(data, number=True)
    data['label'] = ["{}.".format(x + 1) for x in range(data.shape[0])]
    text_style = {
        'color': 'blue',
        'va': 'bottom',
        'ha': 'left',
        'path_effects': [PathEffects.withStroke(linewidth=3, foreground="w")],
        'fontsize': 14
    }

    text_ents = []
    for i, player in enumerate(data.Name.unique()):
        text_style['color'] = colour_list[i]
        p_data = data.loc[data['Name'] == player]
        text_ents += plot_labels(p_data, ax_in, text_style)

    # text_ents = plot_labels(data, ax_in, text_style)

    ward = Image_open(environment['WARD_ICON'])
    ward.thumbnail(size)
    extra_ents = plot_image_scatter(data, ax_in, ward)

    # Adjust the labels
    adjust_text(text_ents, extra_ents=extra_ents, ax=ax_in)

    # Add summary table
    data['label'] = [str(x + 1) for x in range(data.shape[0])]
    table = plot_sum_table(data, ax_in)

    extra_ents += text_ents
    extra_ents.append(table)
    return extra_ents
示例#5
0
    def loadImage(self, imageName):
        glEnable(GL_TEXTURE_2D)
        """Load an image file as a 2D texture using PIL"""
        im = ImageOpen(imageName)
        img_data = numpy.array(im.getdata(), numpy.uint8)

        self.imageID = glGenTextures(1)
        print(self.imageID)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        glBindTexture(GL_TEXTURE_2D, self.imageID)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, im.size[0], im.size[1], 0,
                     GL_RGB, GL_UNSIGNED_BYTE, img_data)

        return self.imageID
示例#6
0
  def loadImage( self, imageName):
    glEnable(self.__texMode)
    """Load an image file as a 2D texture using PIL"""
    im = ImageOpen(imageName)    
    img_data = numpy.array(im.getdata(), numpy.uint8)

    self.imageID = glGenTextures(1)
    print(self.imageID)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glBindTexture(self.__texMode, self.imageID)
    glTexParameterf(self.__texMode, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(self.__texMode, GL_TEXTURE_WRAP_T, GL_REPEAT)
    #glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    #glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexImage2D(
        self.__texMode, 0, GL_RGB, im.size[0], im.size[1], 0,
        GL_RGB, GL_UNSIGNED_BYTE, img_data
    )
    return self.imageID
示例#7
0
 def show_merge(self, flag='GT'):
     if flag == 'GT':
         path = self.path_mask_GT
         plotwindow = self.merge
     elif flag == 'pred':
         path = self.path_mask_pred
         plotwindow = self.merge_pred
     (_, name) = os.path.split(self.image_list[self.current_image_mark])
     try:
         mask = Iopen(os.path.join(path, name))
         image = Iopen(self.image_list[self.current_image_mark])
         mask = mask.resize((511, 431))
         image = image.resize((511, 431))
         merge = array(image)
         mask_arr = array(mask)
         merge[mask_arr == 0] = [0, 0, 0]
         merge = fromarray(merge)
         plotwindow.setPixmap(merge.toqpixmap())
     except FileNotFoundError as e:
         pass
示例#8
0
 def load(path):
     with open(path, 'rb') as f:
         image = PIOpen(f)
         image.load()
         return VideoFrame(image)
示例#9
0
文件: __init__.py 项目: leiradel/mgba
 def load(path):
     with open(path, 'rb') as f:
         image = PIOpen(f)
         image.load()
         return VideoFrame(image)
示例#10
0
 def __init__(self, path):
     image = PIL_Image_open(path).convert("RGBA")
     self.__size = math.Vector(image.size)
     self.__data = image.tobytes("raw")
 def __init__(self, addr):
     # if addr!='':
     self.__im = ImOpen(addr).convert('L')
class FVRT:

    # 初始化各系数

    # 变换后的宽
    WIDTH = 75

    # 变换后的高
    HEIGHT = 170

    # 灰度放大系数
    THREFACTOR = 4

    # 隶属度分割界限
    THREGRAY = 0.3

    # 迭代次数
    ITER = 3

    # Niblack模板边长
    SIDELENGTH = 11

    # 补偿权值
    THREK = 0.05

    # 开运算模板边长
    OPENSIDE = 3

    # 闭运算模板边长
    CLOSEDSIDE = 3

    # 中值滤波模板边长
    BLURSIDE = 5

    # 圈定面积
    MINSIZE = 20

    # 输入原始图像
    def __init__(self, addr):
        # if addr!='':
        self.__im = ImOpen(addr).convert('L')
        # else:
        #     self.__im=image

    # 尺寸归一化
    def SizeNorm(self, width, height):
        self.__im = self.__im.resize((width, height), BILINEAR)

    # 灰度归一化
    def GrayNorm(self):
        pix = array(self.__im)
        norm = Normalize(vmin=pix.min(), vmax=pix.max())
        pix = norm(pix) * 255
        pix = pix.astype(int32)
        self.__im = fromarray(pix)

    # 基于方向的谷型检测
    def DirectValley(self, ThreFactor):
        pix = array(self.__im)
        row = array([0, 2, 4, 6, 8])
        value = array([3, -1, -4, -1, 3])
        A = {}
        for i in range(4):
            if i == 0:
                col = row
            elif i == 1:
                col = array([2, 3, 4, 5, 6])
            elif i == 2:
                col = array([4, 4, 4, 4, 4])
            else:
                col = array([6, 5, 4, 3, 2])
            A[i] = csc_matrix((value, (row, col)), shape=(9, 9)).toarray()
            A[i + 4] = rot90(A[i])

        pixdict = {}
        for i in range(8):
            pixdict[i] = convolve2d(pix, A[i], 'same')

        m, n = pix.shape
        for x in range(m):
            for y in range(n):
                valmax = -1000
                for i in range(8):
                    if pixdict[i][x, y] >= valmax:
                        valmax = pixdict[i][x, y]
                if valmax >= 0:
                    pix[x, y] = valmax
                else:
                    pix[x, y] = 0

        nozero_num = count_nonzero(pix)
        nozero_avg = sum(pix) / nozero_num

        for x in range(m):
            for y in range(n):
                if pix[x, y] >= (ThreFactor * nozero_avg):
                    pix[x, y] = ThreFactor * nozero_avg
        self.__im = fromarray(pix)

    # 图像模糊增强
    def BlurEnhance(self, ThreGray, Iter):
        pix = array(self.__im)
        pix = sin(pix * pi / (2 * 255))
        for i in arange(Iter):
            pix = (sin(pi * (pix - ThreGray)) + 1) / 2
        pix = 255 * arcsin(pix**sqrt(Iter)) * 2 / pi
        self.__im = fromarray(pix)

    # 图像阈值分割
    def ThreSegment(self, SideLength, ThreK):
        pix = array(self.__im)
        thresh_pix = threshold_niblack(pix,
                                       window_size=SideLength * SideLength,
                                       k=ThreK)
        binary_pix = pix > thresh_pix
        pix = binary_pix.astype(int) * 255
        self.__im = fromarray(pix)

    # 图像去噪
    def Denoise(self, OpenSide, ClosedSide, BlurSide):
        im = self.__im
        im = cv2.cvtColor(asarray(im).astype(uint8), cv2.COLOR_GRAY2BGR)
        openkernel = cv2.getStructuringElement(cv2.MORPH_RECT,
                                               (OpenSide, OpenSide))
        opening = cv2.morphologyEx(array(im), cv2.MORPH_OPEN, openkernel)
        closedkernel = cv2.getStructuringElement(cv2.MORPH_RECT,
                                                 (ClosedSide, ClosedSide))
        closed = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, closedkernel)
        result = cv2.medianBlur(closed, BlurSide)
        pix = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)
        self.__im = fromarray(pix)

    # 图像细化
    def Thin(self):
        pix = array(self.__im)
        pix = pix / 255
        pix = morphology.skeletonize(pix)
        pix = pix.astype(int) * 255
        self.__im = fromarray(pix)

    # 二值化图像去除残余斑点
    def CleanSmallObject(self, MinSize):
        pix = array(self.__im) / 255
        pix = pix.astype(bool)
        pix = morphology.remove_small_objects(pix,
                                              min_size=MinSize,
                                              connectivity=2)
        pix = pix.astype(int) * 255
        self.__im = fromarray(pix)

    # 获得图像数组
    def GetArray(self):
        return array(self.__im)

    # 获得图像
    def GetImage(self):
        return self.__im

    # 显示图像
    def ShowImage(self):
        self.__im.show()

    # 设置各系数
    @staticmethod
    def SetFactor(width=75,
                  height=170,
                  ThreFactor=4,
                  ThreGray=0.3,
                  Iter=3,
                  SideLength=11,
                  ThreK=0.05,
                  OpenSide=3,
                  ClosedSide=3,
                  BlurSide=5,
                  MinSize=20):
        FVRT.WIDTH = width
        FVRT.HEIGHT = height
        FVRT.THREFACTOR = ThreFactor
        FVRT.THREGRAY = ThreGray
        FVRT.ITER = Iter
        FVRT.SIDELENGTH = SideLength
        FVRT.THREK = ThreK
        FVRT.OPENSIDE = OpenSide
        FVRT.CLOSEDSIDE = ClosedSide
        FVRT.BLURSIDE = BlurSide
        FVRT.MINSIZE = MinSize

    # 一键操作图像
    @staticmethod
    def OneKey(addr):
        image = FVRT(addr)
        image.SizeNorm(FVRT.WIDTH, FVRT.HEIGHT)
        image.GrayNorm()
        image.DirectValley(FVRT.THREFACTOR)
        image.BlurEnhance(FVRT.THREGRAY, FVRT.ITER)
        image.ThreSegment(FVRT.SIDELENGTH, FVRT.THREK)
        image.Denoise(FVRT.OPENSIDE, FVRT.CLOSEDSIDE, FVRT.BLURSIDE)
        image.Thin()
        image.CleanSmallObject(FVRT.MINSIZE)
        return image.GetImage()