Example #1
0
def testSharpen(name="smokey.gif", degree=50, amount=20):
    """Makes image appear crisper."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    image2 = sharpen(image, degree, amount)
    image2.draw()
Example #2
0
 def __init__(self, width, height):
     self.img = Image()
     self.width = width
     self.height = height
     self.length = self.height*self.width
     self.A = 0  #matrix variância
     self.m = 0  #vetor média
Example #3
0
def main(filename = "smokey.gif"):
    image = Image(filename)
    print "Close the image window to continue. "
    image.draw()
    grayscale(image)
    print "Close the image window to quit. "
    image.draw()
Example #4
0
def rotate(iImg, angle):
    LOG(None, 'Rotation Angle: ' + str(angle))
    if 90 == angle:
        oImg = Image(Image.BY_DATA, cv2.rotate(iImg.data,rotateCode = cv2.ROTATE_90_CLOCKWISE))
        
    elif 180 == angle:
        oImg = Image(Image.BY_DATA, cv2.rotate(iImg.data,rotateCode = cv2.ROTATE_180))
        
    elif 270 == angle:
        oImg = Image(Image.BY_DATA, cv2.rotate(iImg.data,rotateCode = cv2.ROTATE_90_COUNTERCLOCKWISE))
        
    else:
        # Calculate Rotation Matrix
        h, w, _ = iImg.data.shape
        cx = w >> 1
        cy = h >> 1
        rotMatrix = cv2.getRotationMatrix2D((w >> 1, h >> 1), -angle, 1.0)
        cos = np.abs(rotMatrix[0, 0])
        sin = np.abs(rotMatrix[0, 1])
     
        # compute the new bounding dimensions of the image
        nW = int((h * sin) + (w * cos))
        nH = int((h * cos) + (w * sin))
     
        # adjust the rotation matrix to take into account translation
        rotMatrix[0, 2] += (nW / 2) - cx
        rotMatrix[1, 2] += (nH / 2) - cy
        
        # perform the actual rotation and return the image
        oImg = Image(Image.BY_DATA, cv2.warpAffine(iImg.data, rotMatrix, (nW, nH)))
        
    
    return oImg
def main():
    colors = [(255, 0, 0), (255, 255, 0), (0, 255, 0), (0, 255, 255),
              (0, 0, 255), (255, 0, 255)]

    img = Image(500, 200)
    rainbow(img, colors)
    img.draw()
def main(filename = "smokey.gif"):
    image = Image(filename)
    print "Close the image window to continue. "
    image.draw()
    blackAndWhite(image)
    print "Close the image window to quit. "
    image.draw()
Example #7
0
def testSharpen (name = "smokey.gif", degree = 50, amount = 20):
    """Makes image appear crisper."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    image2 = sharpen(image, degree, amount)
    image2.draw()
Example #8
0
def main():
    filename = input("Enter the image file name: ")
    image = Image(filename)
    #lighten(image, 20) example
    #darken(image2, 64) example
    colorFilter(image3, (255, 0, 0)) #example
    image.draw()
Example #9
0
def main():
    filename = input("Enter the image file name: ")
    image = Image(filename)
    print("Close the window to view the changes to the image.")
    image.draw()
    newimage = enlarge(image, 2)
    newimage.draw()
Example #10
0
 def showPicInfo(self):
     from images import Image
     image = Image(self._textField.getText())
     w = image.getWidth()
     h = image.getHeight()
     print(self._textField.getText())
     print("The width is ", w)
     print("The height is ", h)
def testDetect(name="smokey.gif", amount=20):
    """Loads and draws an image, then
    detects edges and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    image2 = detectEdges(image, amount)
    image2.draw()
Example #12
0
def testPosterize(name = "smokey.gif", triple = (0,0,0)):
    """Loads and draws an image, then converts it to a color
    of the user's choosing and white, and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    posterize(image, triple)
    image.draw()
Example #13
0
def testDetect(name = "smokey.gif", amount = 20):
    """Loads and draws an image, then
    detects edges and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    image2 = detectEdges(image, amount)
    image2.draw()
Example #14
0
def main():
    filename = input("Enter the image file name: ")
    red = int(input("Enter an integer [0..255] for red: "))
    green = int(input("Enter an integer [0..255] for green: "))
    blue = int(input("Enter an integer [0..255] for blue: "))
    image = Image(filename)
    posterize(image, (red, green, blue))
    image.draw()
Example #15
0
def testBlackAndWhite(name = "smokey.gif"):
    """Loads and draws an image, then
    converts it to black and white and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    blackAndWhite(image)
    image.draw()
Example #16
0
def testGrayscale(name = "smokey.gif"):
    """Loads and draws an image, converts it to pyschologically correct
    grayscale, and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    grayscale(image)
    image.draw()
Example #17
0
def testSepia (name = "smokey.gif"):
    """Loads and draws an image, converts it to grayscale, then converts it to
    sepia, and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    sepia(image)
    image.draw()
def rotateRight(image):
    """Rotates the image 90 degrees """
    newImage = Image(image.getHeight(), image.getWidth())
    for y in range(image.getHeight()):
        for x in range(image.getWidth()):
            (r, g, b) = image.getPixel(x, y)
            newImage.setPixel(image.getHeight() - y - 1, x, (r, g, b))

    return newImage
def testRotateRight(name="smokey.gif"):
    """Loads and draws an image, then
    rotates it 90 degrees to the right and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    image2 = rotateRight(image)
    image2.draw()
    image2.save(filename="rotateRight_" + name)
def testSharpen(name="smokey.gif"):
    """Loads and draws an image, then sharpens
    the image and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    image2 = sharpen(image, 20, 50)
    image2.draw()
    image2.save(filename="sharpen_" + name)
Example #21
0
    def load(cls, path, world, fargs):
        path = Path(path)

        thumbnail = Image(path / 'S0.jpg', MEDIUM)
        screenshots = (Image(path / 'S{}.jpg'.format(i), MEDIUM) for i in range(1, 6)) if world else None
        panorama = Image(path / 'S6.jpg', PANORAMA) if world else None
        icon = Image(path / 'S7.jpg', L_SQ) if world and (path / 'S7.jpg').is_file() else None

        return cls(thumbnail, icon, panorama, screenshots, fargs)
Example #22
0
def main(filename = "smokey.gif"):
    image = Image(filename)
    print "Close the image window to continue. "
    image.draw()
    image2 = shrink(image, 2)
    print "Close the image window to continue. "
    image2.draw()
    image3 = shrink(image, 3)
    print "Close the image window to continue. "
    image3.draw()
    print "Close the image window to quit. "
Example #23
0
def main(filename="smokey.gif"):
    image = Image(filename)
    print "Close the image window to continue. "
    image.draw()
    image2 = detectEdges(image, 10)
    print "Close the image window to continue. "
    image2.draw()
    image3 = detectEdges(image, 20)
    print "Close the image window to continue. "
    image3.draw()
    print "Close the image window to quit. "
Example #24
0
def main(filename="smokey.gif"):
    image = Image(filename)
    print "Close the image window to continue. "
    image.draw()
    image2 = shrink(image, 2)
    print "Close the image window to continue. "
    image2.draw()
    image3 = shrink(image, 3)
    print "Close the image window to continue. "
    image3.draw()
    print "Close the image window to quit. "
Example #25
0
def main(filename = "smokey.gif"):
    image = Image(filename)
    print "Close the image window to continue. "
    image.draw()
    image2 = detectEdges(image, 10)
    print "Close the image window to continue. "
    image2.draw()
    image3 = detectEdges(image, 20)
    print "Close the image window to continue. "
    image3.draw()
    print "Close the image window to quit. "
Example #26
0
def main():
    filename = input("Enter the image file name: ")
    image = Image(filename)
    # Invert image
    invert(image)
    image.draw()
    # Covert to greyscale, then invert
    """grayscale(image)
    invert(image)
    image.draw()"""
    # Convert to black and white, then invert
    """blackAndWhite(image)
Example #27
0
class PCA():
    def __init__(self, width, height):
        self.img = Image()
        self.width = width
        self.height = height
        self.length = self.height*self.width
        self.A = 0  #matrix variância
        self.m = 0  #vetor média
    def show(self, img):
        self.img.showImage(img, self.height, self.width)
    def getLength(self):
        return self.length
    def getMatrix(self, M):
        A = np.zeros((self.length,self.length))
        M = M.T
        for i in range(0,10):   #função que retorna matrix de covariancia
            A = A + np.outer(M[:,i],M[:,i])#np.outer(M[i,:],M[i,:]) #para a múltiplicação da matrix MxM^T eu utilizei uma função pronta de Python
        return A
    def getEignValues(self, M): #função que retorna o valor dos autovalores da matrix
        V, D = np.linalg.eig(M)
        return np.diagonal(D)
    def meanVector(self, image_set, N):
        F = np.zeros(self.length)
        self.A = np.zeros((10, self.length))
        for n in range(1,N+1):
            D = np.array(self.img.readImage(image_set,n, self.length))
            F = F + D
            self.A[n-1,:] = D
            #self.show(D)
        self.m = F/N
    def getMean(self):
        return self.m
    def compare(self, imageCompare):
        self.Thau = imageCompare - self.m
        return self.getWeights(self.Thau)
    def setVariance(self):
        self.m = np.outer(np.ones(10),self.m)
        self.A = self.A - self.m
        return self.A
    def getVariance(self):
        return self.A
    def getPCA(self, eig, threshold):
        total = sum(eig)
        for i in range(self.length):
            if(threshold < sum(eig[self.length-i:self.length])/total):
                return i
            elif(i == self.length):
                return 0
    def getWeights(self, eigvector):
        print(eigvector.shape, self.A[1,:].shape)
        return eigvector.T.dot(self.A[1,:])
Example #28
0
    def load(cls, path, name, uuid_s=None, languages=None):
        path = Path(path)

        new_path = path.parents[0]
        new_path = new_path / "world"

        if new_path.is_dir():
            worlds = list(filter(is_world, new_path.iterdir()))

        if len(worlds) > 1:
            raise MultipleWorldsError(new_path)

        if len(worlds) == 1:
            w = worlds[0]
        new_path = w

        if languages is None:
            languages = ['en_US']

        cap_name = upper_name(name)

        skins = []
        texts = SkinTexts(name, languages=languages, copy_langs=None)
        for p in path.glob('*.png'):
            skin_name = p.stem
            img = Image(p, ANY)

            skin = Skin(skin_name, img)

            texts.add_skin(skin)
            skins.append(skin)

        return cls(new_path, skins, name, cap_name, uuid_s, texts)
def main():
    filename = input("Enter the image file name: ")
    # image1 = Image(filename)
    # grayscale1(image1)
    image2 = Image(filename)
    grayscale2(image2)
    image.draw()
def testSepia(name="smokey.gif"):
    """Loads and draws an image, then
    converts it to sepia and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    sepia(image)
    image.draw()
    image.save(filename="sepia_" + name)
def testColorScale(name="smokey.gif"):
    """Loads and draws an image, then applies colorscale
    to the image and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    colorscale(image, (randint(0, 255), randint(0, 255), randint(0, 255)))
    image.draw()
    image.save(filename="colorscale_" + name)
def testPosterize(name="smokey.gif"):
    """Loads and draws an image, then
    converts it to black and white and redraws it."""
    image = Image(name)
    print("Close the image window to see the transformation")
    image.draw()
    posterize(image, (0, 0, 255))
    image.draw()
    image.save(filename="posterize_" + name)
Example #33
0
    def __init__(self, odooenv, name):
        """ Busca el cliente en la estructura de directorios, pero si no lo
            encuentra pide un directorio donde esta el repo que lo contiene
        """
        # parent es siempre un objeto OdooEnv
        self._parent = odooenv
        self._name = name

        # si estamos en test accedo a data
        if name[0:5] == 'test_':
            path = os.path.dirname(os.path.abspath(__file__))
            path = path.replace('scripts', 'data')
            manifest = self.get_manifest(path)
        else:
            manifest = self.get_manifest(BASE_DIR)
        if not manifest:
            msg.inf('Can not find client {} in this host. Please provide path '
                    'to repo\n where it is or hit Enter to exit.'
                    '\n'.format(self._name))

            path = raw_input('path = ')
            manifest = self.get_manifest(path)
            if not manifest:
                msg.err('Can not find client {} in this host'.format(name))

            msg.inf('Client found!')
            msg.inf('Name {}\nversion {}\n'.format(manifest.get('name'),
                                                   manifest.get('version')))

        # Chequar que este todo bien
        if not manifest.get('docker'):
            msg.err('No images in manifest {}'.format(self.name))

        if not manifest.get('repos'):
            msg.err('No repos in manifest {}'.format(self.name))

        self._port = manifest.get('port')
        if not self._port:
            msg.err('No port in manifest {}'.format(self.name))

        self._version = manifest.get('version')[0:3]
        if not self._version:
            msg.err('No version tag in manifest {}'.format(self.name))

        # Crear imagenes y repos
        self._repos = []
        for rep in manifest.get('repos'):
            self._repos.append(Repo(rep))

        self._images = []
        for img in manifest.get('docker'):
            self._images.append(Image(img))

        # todo codigo repetido
        # get first word of name in lowercase
        name = manifest.get('name').lower()
        if not self._name == name.split()[0]:
            msg.err('You intend to install client {} but in manifest, '
                    'the name is {}'.format(self._name, manifest.get('name')))
Example #34
0
def flip(iImg, flipAxis):
    if (FLIP_V == flipAxis) or (FLIP_H == flipAxis):
        oImg = Image(Image.BY_DATA, cv2.flip(iImg.data, flipAxis))
        
    else:
        oImg = None
        
    return oImg
def main(filename):
    image = Image(filename)
    print('Close the image window to continue. ')
    image.draw()
    greyscale(image)
    print('Close the image window to continue. ')
    image.draw()
    sepia(image)
    print('Close the image window to quit. ')
    image.draw()
Example #36
0
def enlarge(image, factor):
    """Builds and returns a copy of the image which is larger
    by the factor."""
    oldWidth = image.getWidth()
    oldHeight = image.getHeight()
    new = Image(oldWidth * factor, oldHeight * factor)
    oldY = 0
    newY = 0
    while oldY < oldHeight:
        for countY in range(factor):
            oldLeft = 0
            oldRight = oldWidth - 1
            newLeft = 0
            newRight = new.getWidth() - 1
            while oldLeft < oldRight:
                leftPixel = image.getPixel(oldLeft, oldY)
                rightPixel = image.getPixel(oldRight, oldY)
                for count in range(factor):
                    new.setPixel(newLeft, newY, leftPixel)
                    new.setPixel(newRight, newY, rightPixel)
                    newLeft += 1
                    newRight -= 1
                oldLeft += 1
                oldRight -= 1
            newY += 1
        oldY += 1
    return new
Example #37
0
        def on_each_saved(job_runner, index, filename):
            logger.info('received file for index {}: {}'.format(
                index, filename))

            image = Image(path=filename, file_required=True)
            self.progress = job_runner.finished
            self.saved_images.append(image.id)
            main_images_db.add(image)
            on_update()
Example #38
0
def shrink(image, factor):
    """Builds and returns a new image which is smaller
    copy of the argument image, by the factor argument."""
    width = image.getWidth()
    height = image.getHeight()
    new = Image(width / factor, height / factor)
    oldY = 0
    newY = 0
    while oldY < height - factor:
        oldX = 0
        newX = 0
        while oldX < width - factor:
            oldP = image.getPixel(oldX, oldY)
            new.setPixel(newX, newY, oldP)
            oldX += factor
            newX += 1
        oldY += factor
        newY += 1
    return new
Example #39
0
def shrink(image, factor):
    """Builds and returns a new image which is smaller
    copy of the argument image, by the factor argument."""
    width = image.getWidth()
    height = image.getHeight()
    new = Image(width / factor, height / factor)
    oldY = 0
    newY = 0
    while oldY < height - factor:
        oldX = 0
        newX = 0
        while oldX < width - factor:
            oldP = image.getPixel(oldX, oldY)
            new.setPixel(newX, newY, oldP)
            oldX += factor
            newX += 1
        oldY += factor
        newY += 1
    return new
Example #40
0
        def saveAnswer(answer):
            # fill with black to wipe the screen. Otherwise the answer labels stack on each other
            # We wont need this when we are not outputting the answer.
            if (angle.checkAnswer(answer)):
                print('correct')

                score.increment()
                angle.setRandomAngle()
                print self.planetNear.image
                self.planetNear.originalImage = self.planetFar.originalImage
                self.planetFar = Image(
                    PLANET_PREFIX + str(randint(0, PLANET_NUMBER - 1)) +
                    PLANET_SUFFIX, angleDisplay)
                putPlanets(self.planetNear, self.planetFar)

            else:
                print('wrong')
                loseGame('')
                score.reset()
Example #41
0
    def run(self):
        self._reload = False

        for file in self._files:
            try:
                with file.open(mode='rb') as f:

                    image = Image(f)
                    image.display(self)

            except ImageException as exception:
                print(exception)
                continue

            except FileNotFoundError as exception:
                print(f'file not found: {exception.filename}')
                continue

            if self._reload:
                return
Example #42
0
def serve_crop(request, filename, width, height, root=settings.MEDIA_ROOT):
    width, height = int(width), int(height)
    filename = filename.replace("/../", "/")
    filename = filename.replace("//", "/")
    while filename.startswith(os.sep):
        filename = filename[1:]
    image = Image.open(filename, root=root)
    image = image.image.transform((width, height), ImageCalc.EXTENT, (0, 0, image.image.size[0], image.image.size[1]))
    # Return the response
    response = HttpResponse(mimetype="image/jpg")
    image.save(response, "JPEG")
    return response
Example #43
0
def serve_image(request, filename, width=None, height=None, root=settings.MEDIA_ROOT):
    width, height = int(width), int(height)
    # Sanitize file path
    filename = filename.replace("/../", "/")
    filename = filename.replace("//", "/")
    while filename.startswith(os.sep):
        filename = filename[1:]
    # open with PIL
    image = Image.open(filename, root=root)
    if width:
        # Scale height
        if not height:
            height = image.scale_height(width)
        resized = image.resize(width, height)
    else:
        resized = image.image
    # Return the response
    response = HttpResponse(mimetype="image/jpg")
    resized.save(response, "JPEG")
    return response