def OpenClicked(self):

        print "File Open Not Functional"

        
        path = QFileDialog.getOpenFileName(self,
            "Open File", self.path , str("Images (*raw *png)"))

      
        
        ftype = str(path.split(".")[-1])        
        
        if ftype == "raw":
            self.ImageGenerator(path, None, None, None)
      #  image_file = open(path)

        if ftype == "png":
            #import png as numpy array
            Image = mpimg.imread(str(path))
            #scale pixel values which are originally between 0 and 1 so that 
            #their values fall between 0 and 255 
            scaledimage = 255*Image
            #reformat pixel data type from float to numpy.uint8
            scaled_num_array = numpy.array(scaledimage,dtype=numpy.uint8)

            shape = (scaled_num_array.shape[0], scaled_num_array.shape[1])
            channel1 = scaled_num_array[:,:,2]
            channel2 = scaled_num_array[:,:,1]
            channel3 = scaled_num_array[:,:,0]
            alpha_array = 255*(numpy.ones(shape, dtype=numpy.uint8))

            # apparently alpha gets stacked last. load BGRA because the byte 
            #order in memory for each channel is stored in memory as BGRA 
            #0xBBGGRRAA by little-endian CPU's such as intel processors for 
            #future overlay work do  
            #example>>>>> image_ARGB = numpy.dstack(/
            #[image_Blue,image_Green,image_Red,alpha_array])
            image_ARGB_3D = numpy.dstack([channel1,channel2,\
                                            channel3,alpha_array])

            # reshape to a 2D array that has 4 bytes per pixel
            image_ARGB_2D = numpy.reshape(image_ARGB_3D,(-1,\
                                            scaled_num_array.shape[1]*4)) 
            #Reshape does not copy, only manipulates data structure holding the
            #data

            #Numpy buffer QImage declaration
            Image = QImage(image_ARGB_2D.data, scaled_num_array.shape[1],\
                            scaled_num_array.shape[0],\
                            QImage.Format_ARGB32)
            Image.ndarray = image_ARGB_2D  
            # necessary to create a persistant reference to the data per QImage
            #class
            target = QRectF(0, 0, Image.width(), Image.height())
            source = QRectF(0, 0, Image.width(), Image.height())
            compImage = CompImage(target, Image, source, self.selectedbrowser,\
                                    self.livebrowser, self.pixelValueBrowser, channel1) 
            self.scene.clear()
            self.scene.addItem(compImage)
            self.Image = Image
Example #2
0
    def _publish_image(self):
        """
        Publish latest camera image as Image with CameraInfo.

        """
        # only publish if we have a subscriber
        if self._image_pub.get_num_connections() == 0:
            return

        # get latest image from vectors's camera
        camera_image = self._vector.camera.latest_image
        if camera_image is not None:
            # convert image to gray scale
            img = camera_image.convert('RGB')
            # 640,360 image size?
            # img = camera_image
            ros_img = Image()
            ros_img.encoding = 'rgb8'
            ros_img.width = img.size[0]
            ros_img.height = img.size[1]
            ros_img.step = ros_img.width
            ros_img.data = img.tobytes()
            ros_img.header.frame_id = 'vector_camera'
            # vector_time = camera_image.image_recv_time
            # ros_img.header.stamp = rospy.Time.from_sec(vector_time)
            ros_img.header.stamp = rospy.Time.now()
            # publish images and camera info
            self._image_pub.publish(ros_img)
Example #3
0
def create_derived_image(image,pilDerivedImage,type,eraseOldVersions = True):
    
    if eraseOldVersions:
        image.derived_images.filter(type = type).delete()
        
    (directory,basename,extension) = image.splitPath()

    derivedImageFilename = basename+"_"+type+"."+extension
    derivedImagePath = directory+"/"+derivedImageFilename
    
    cnt = 1
    
    while os.path.exists(derivedImagePath): 
        derivedImageFilename = basename+"_"+type+("_%d" % cnt)+"."+extension
        derivedImagePath = directory+"/"+derivedImageFilename
        cnt+=1

    derivedImageUrl = settings.FILE_UPLOAD_URL+"/"+derivedImageFilename

    pilDerivedImage.save(derivedImagePath)

    derivedImage = Image()
    derivedImage.path = derivedImagePath
    derivedImage.user = image.user
    derivedImage.base_image = image
    derivedImage.type = type
    derivedImage.url = derivedImageUrl
    derivedImage.width = pilDerivedImage.size[0]
    derivedImage.height = pilDerivedImage.size[1]
    derivedImage.save()
    
    return derivedImage
Example #4
0
    def test_resize_in_edit_mode(self):
        image = Image(organization=self.organization)
        image.resize_image = MagicMock()
        file = ContentFile(self.create_random_image(100, 100).read())

        image.file.save('random_image.png', file, save=False)
        image.save()

        image.resize_image.assert_called_with()

        image.resize_image.reset_mock()

        image.expiration = '10:00'
        image.save()

        self.assertFalse(
            image.resize_image.called,
            'Saving an existing image should not call '
            'resize_image, except if width has changed')

        image.resize_image.reset_mock()

        image.width = 200
        image.save()

        self.assertTrue(
            image.resize_image.called,
            'Saving an existing image with a new width should '
            'call resize_image')
 def write_rejected_images(self, filter_dic):
     self.copy_cell_style("A24", 'A' + str(self.i))
     self.page['A' +
               str(self.i)] = "Rejected Images- Oversized Pore Observations"
     self.page.merge_cells('A' + str(self.i) + ':E' + str(self.i))
     self.i = self.i + 1
     for frame in filter_dic['frame_ls']:
         if len(frame.image_data_ls) != 0:
             self.page['A' + str(self.i)] = "Frame: "
             self.page["B" + str(self.i)] = frame.name
             self.i = self.i + 2
         for image in frame.image_data_ls:
             if not image['pass']:
                 self.rejected_header(image)
                 #add rejected image into spreadsheet
                 fail_img = Image('./job-data/' + self.job_name + '/' +
                                  frame.name + '/' + image['img_name'])
                 fail_img.anchor = 'C' + str(self.i)
                 fail_img.width = 400
                 fail_img.height = 300
                 self.page.add_image(fail_img)
                 j = 0
                 for pore in image['violated_circles']:
                     self.page['A' + str(self.i + j)] = pore[1]
                     self.page['B' + str(self.i + j)] = '( ' + str(
                         pore[0][0]) + ', ' + str(pore[0][1]) + " )"
                     j += 1
                 if j > 17:
                     self.i += j
                 else:
                     self.i += 17
Example #6
0
    def get_pil_image(self):
        """ Get image in python friendly format
        Assumptions are that the image has byte pixels.

        :return: array containing image
        :rtype: pil image
        """
        def pil_mode_from_image(img):
            """
            Determine image format from pixel properties

            May return None if our current encoding does not map to a PIL image
            mode.
            """
            if img.pixel_type() == img.PIXEL_UNSIGNED and img.pixel_num_bytes() == 1:
                if img.depth() == 3 and img.d_step() == 1 and img.w_step() == 3:
                    return "RGB"
                elif img.depth() == 4 and img.d_step() == 1 and img.w_step() == 4:
                    return "RGBA"
                elif img.depth() == 1 and img.w_step() == 1:
                    return "L"
            elif img.depth() == 1 and img.w_step() == 1:
                if img.pixel_type() == img.PIXEL_BOOL and img.pixel_num_bytes() == 1:
                    return "1"
                elif img.pixel_type() == img.PIXEL_SIGNED and img.pixel_num_bytes() == 4:
                    return "I"
                elif img.pixel_type() == img.PIXEL_FLOAT and img.pixel_num_bytes() == 4:
                    return "F"
            return None

        img = self
        mode = pil_mode_from_image(img)

        if not mode:
            # make a copy of this image using contiguous memory with interleaved channels
            img = Image(self.width(), self.height(), self.depth(),
                        True, self.pixel_type(), self.pixel_num_bytes())
            img.copy_from(self)
            mode = pil_mode_from_image(img)

        if not mode:
            raise RuntimeError("Unsupported image format.")

        img_first_byte = img.first_pixel_address()

        size = img.size()
        if size == 0:
            size = (img.h_step() * img.height()) * img.pixel_num_bytes()
        # get buffer from image
        pixels = ctypes.pythonapi.PyBuffer_FromReadWriteMemory
        pixels.argtypes = [ ctypes.c_void_p, ctypes.c_ssize_t ]
        pixels.restype = ctypes.py_object
        img_pixels = pixels( img_first_byte, size )

        return _pil_image_from_bytes(mode, (img.width(), img.height()),
                                     img_pixels, "raw", mode,
                                     img.h_step() * img.pixel_num_bytes(), 1)
Example #7
0
def upload_image(imageData,user = None,save = True,path = None):
    try:
        extension = re.search(r"\.(\w+)$",imageData.name).group(1)
    except:
        raise Exception("Cannot determine extension from filename: %s" % imageData.name)

    try:
        temporaryPath = generate_random_filename(settings.FILE_TEMPORARY_UPLOAD_PATH,extension)
        if path:
            (directory,filename) = os.path.split(path)
            match = re.search(r"^(.*)\.(\w+)$",filename)
            imageFilenameKey = match.group(1)
        else:            
            imageFilenameKey = generate_random_filename_key(settings.FILE_UPLOAD_PATH,extension = "jpg")
        
        imagePath = settings.FILE_UPLOAD_PATH+"/"+imageFilenameKey+"."+settings.IMAGE_EXTENSION
        imageUrl = settings.FILE_UPLOAD_URL+"/"+imageFilenameKey+"."+settings.IMAGE_EXTENSION
        
        temporaryFile = open(temporaryPath,'wb')
    
        for chunk in imageData.chunks():
            temporaryFile.write(chunk)
        
        temporaryFile.close()
        
        try:
            pilImage = PIL.Image.open(temporaryPath)
            
            aspectRatio = float(pilImage.size[0])/float(pilImage.size[1])
            
            if aspectRatio > 1.:
                aspectRatio = 1./aspectRatio
                
            if aspectRatio < settings.IMAGE_MINIMUM_ASPECT_RATIO:
                raise AspectRatioException("Aspect ratio of the image is too small!")
                
            pilRescaledImage = shrink_image(pilImage,settings.IMAGE_MAXIMUM_DIMENSIONS)
            
            pilRescaledImage.save(imagePath,settings.IMAGE_FORMAT)
    
            image = Image()
            image.user = user
            image.path = imagePath
            image.url = imageUrl
            image.width = pilRescaledImage.size[0]
            image.height = pilRescaledImage.size[1]
            if save:
                image.save()
            return image
        except:
            raise
    finally:
        if os.path.exists(temporaryPath):
            os.remove(temporaryPath)
Example #8
0
def numpy_to_imgmsg(image, stamp=None):
    from sensor_msgs.msg import Image
    rosimage = Image()
    rosimage.height = image.shape[0]
    rosimage.width = image.shape[1]
    if image.dtype == numpy.uint8:
        rosimage.encoding = '8UC%d' % image.shape[2]
        rosimage.step = image.shape[2] * rosimage.width
        rosimage.data = image.ravel().tolist()
    else:
        rosimage.encoding = '32FC%d' % image.shape[2]
        rosimage.step = image.shape[2] * rosimage.width * 4
        rosimage.data = numpy.array(image.flat, dtype=numpy.float32).tostring()
    if stamp is not None:
        rosimage.header.stamp = stamp
    return rosimage
Example #9
0
    def test_image_resizing(self):
        image = Image(organization=self.organization)
        file = ContentFile(self.create_random_image(100, 100).read())

        image.file.save('random_image.png', file, save=False)
        image.save()

        image_file = PIL.Image.open(image.file.file)
        self.assertEqual((100, 100), image_file.size)

        image = Image(organization=self.organization)
        file = ContentFile(self.create_random_image(100, 100).read())

        image.file.save('random_image.png', file, save=False)
        image.width = 50
        image.save()

        image_file = PIL.Image.open(image.file.file)
        self.assertEqual((50, 50), image_file.size)
Example #10
0
    def callback(self, data):

        #points.append(171,224)
        data.data

        points_msg = Image()
        bridge = CvBridge()
        IMAGE_HEIGHT = 171
        IMAGE_WIDTH = 224
        points_msg.header.stamp = rospy.Time.now()
        points_msg.header.frame_id = "camera_depth_optical_frame"
        points_msg.encoding = "32FC1"
        points_msg.height = IMAGE_HEIGHT
        points_msg.width = IMAGE_WIDTH
        points_msg.data = bridge.cv2_to_imgmsg(points_img, '32FC1').data
        points_msg.is_bigendian = 0
        points_msg.step = points_msg.width * 4

        cvImage = bridge.cv2_to_imgmsg(points_img, encoding='passthrough')
        cvImPub = rospy.Publisher('/cvImage_array', Image, queue_size=1)
        cvImPub.publish(points_msg)
Example #11
0
def _upload_frame_set(image_store, project_store, project, label, zip_file):
    project_id = project.id
    _ensure_project_image_exists(project_id)

    image = Image()
    image.label = label
    image.original_file_names = {}
    image.project_id = project_id
    image_id = image_store.create(image.to_json())
    image.id = image_id

    # save zip file in project folder
    zip_path = os.path.join(get_image_folder(), project_id,
                            "{}.zip".format(image_id))
    zip_file.save(zip_path)

    # extract zip file
    extract_dir = os.path.join(get_image_folder(), project_id, image_id)
    os.mkdir(extract_dir)
    with zipfile.ZipFile(zip_path, "r") as zip_ref:
        zip_ref.extractall(extract_dir)

    # capture list of files and mime types
    mime_types = {}
    file_names = []
    for file in os.listdir(extract_dir):
        file_names.append(file)
        current_mime_type = ImageAdapter.get_mime_type(file)
        if current_mime_type is not None:
            if current_mime_type not in mime_types:
                mime_types[current_mime_type] = 0
            mime_types[current_mime_type] += 1

    # get mime type and file extension
    all_types = []
    for mime_type in mime_types:
        all_types.append({"type": mime_type, "count": mime_types[mime_type]})
    sorted_types = list(
        sorted(all_types, key=lambda x: x["count"], reverse=True))
    if len(sorted_types) == 0:
        raise ValueError("Zip file contains no valid images")
    mime_type = sorted_types[0]["type"]
    file_extension = ImageAdapter.get_image_extensions()[mime_type]

    # filter out non images
    file_names = list(
        filter(lambda x: ImageAdapter.get_mime_type(x) == mime_type,
               file_names))

    # update meta image
    image.content_type = mime_type
    image.num_frames = len(file_names)
    image_store.update_full(image)

    # sort by length and then file name
    for index, frame in enumerate(
            sorted(list(map(lambda fn: (len(fn), fn), file_names)),
                   key=itemgetter(0, 1))):
        # rename into 0.jpg, 1.jpg, ...
        os.rename(
            os.path.join(extract_dir, frame[1]),
            os.path.join(extract_dir, "{}{}".format(index, file_extension)))
        image.original_file_names[str(index)] = frame[1]

    # get image dimensions
    stored_image = PIL.Image.open(get_image_path(image, 0))
    width, height = stored_image.size
    image_store.update_dimension(image.id, width, height)
    image_store.update_original_file_names(image.id, image.original_file_names)

    image.width = width
    image.height = height

    # update project
    project.image_count += 1
    project_store.update_counts(project)

    # clean up
    os.unlink(zip_path)
    return image
    def ImageGenerator(self, path1, path2, path3, path4):
        width = 1000
        height = 1000
        shape = (width, height)
        alpha_array = 255*(numpy.ones(shape, dtype=numpy.uint8))
        zero_array = numpy.zeros(shape, dtype=numpy.uint8)
        
        Red = zero_array
        Blue = zero_array
        Green = zero_array
        Yellow = zero_array
        Cyan = zero_array
        Magenta = zero_array
        White = zero_array
 
        image_array_2D1 = zero_array
        
        #Blue
        try:
            image_file = open(path1)
            # load a 1000000 length array
            image_array_1D1 = numpy.fromfile(file=image_file,\
                                                dtype=numpy.uint16)
            image_file.close()
            image_array_2D1 = image_array_1D1.reshape(shape)
            image_8bit1 = (image_array_2D1 >> 6)

        except:
            image_8bit1 = 0*alpha_array
        
        #Green
        try:
            image_file = open(path2)
            # load a 1000000 length array
            image_array_1D2 = numpy.fromfile(file=image_file,\
                                                dtype=numpy.uint16)
            image_file.close()
            image_array_2D2 = image_array_1D2.reshape(shape)
            image_8bit2 = (image_array_2D2 >> 6)
        except:
            image_8bit2 = 0*alpha_array         
        
        try:
            image_file = open(path3)
            image_array_1D3 = numpy.fromfile(file=image_file,\
                                                dtype=numpy.uint16)
            image_file.close()
            image_array_2D3 = image_array_1D3.reshape(shape)
            image_8bit3 = (image_array_2D3 >> 6)
        except:
            image_8bit3 = 0*alpha_array
            image_array_2D3 = alpha_array.reshape(shape)
        
            
        #Georg

        try:
            image_file = open(path4)
            # load a 1000000 length array
            image_array_1D4 = numpy.fromfile(file=image_file,\
                                                dtype=numpy.uint16)
            image_file.close()
            image_array_2D4 = image_array_1D4.reshape(shape)
            image_8bit4 = (image_array_2D4 >> 6)
        except:
            image_8bit4 = 0*alpha_array


        channelcombolist = [self.channel1combobox, self.channel2combobox,\
                                self.channel3combobox, self.channel4combobox]
        imagelist = [image_8bit1, image_8bit2, image_8bit3, image_8bit4]
        for item in range(4):
            if channelcombolist[item].currentText() == "Red":
                Red = Red + imagelist[item]
            elif channelcombolist[item].currentText() == "Blue":
                Blue = Blue + imagelist[item]
            elif channelcombolist[item].currentText() == "Green":
                Green = Green + imagelist[item]
            elif channelcombolist[item].currentText() == "Yellow":
                Yellow = Yellow + imagelist[item]
            elif channelcombolist[item].currentText() == "Cyan":
                Cyan = Cyan + imagelist[item]
            elif channelcombolist[item].currentText() == "Magenta":
                Magenta = Magenta + imagelist[item]
            elif channelcombolist[item].currentText() == "White":
                White = White + imagelist[item]
       
        
        image_ARGB_3D = numpy.dstack([(Blue + Cyan + Magenta + White)\
                                        .clip(0,255).astype(numpy.uint8),\
                                        (Green + Cyan + Yellow + White)\
                                        .clip(0,255).astype(numpy.uint8),\
                                        (Red + Magenta + Yellow + White)\
                                        .clip(0,255).astype(numpy.uint8),\
                                        alpha_array])
        
        # reshape to a 2D array that has 4 bytes per pixel
        image_ARGB_2D = numpy.reshape(image_ARGB_3D,(-1,width*4))
 
        #Numpy buffer QImage declaration
        Image = QImage(image_ARGB_2D.data, width, height, QImage.Format_ARGB32)
        Image.ndarray = image_ARGB_2D  

        target = QRectF(0, 0, Image.width(), Image.height())
        source = QRectF(0, 0, Image.width(), Image.height())
    
        compImage = CompImage(self, target, Image, source,\
                                self.selectedbrowser, self.livebrowser, \
                                self.pixelValueBrowser, image_array_2D1) 
        self.scene.clear()
        self.scene.addItem(compImage)
        self.Image = Image

        self.compinstanceL = []
        
        QV1 = QuadView(self,image_8bit1, zero_array, alpha_array, \
                            self.compositeview1, self.label11, \
                            self.SelectedTextBrowser_2, self.LivetextBrowser_2)
        self.compositescene1.clear()
        self.compositescene1.addItem(QV1)
        
        self.compositeview1.resetMatrix()
        matrix = self.compositeview1.matrix()
        horizontal = 0.5
        vertical = 0.5
        matrix.scale(horizontal, vertical)
        self.compositeview1.setMatrix(matrix)
        
        QV2 = QuadView(self, image_8bit2, zero_array, alpha_array,\
                            self.compositeview2, self.label12,\
                            self.SelectedTextBrowser_2, self.LivetextBrowser_2)
        self.compositescene2.clear()
        self.compositescene2.addItem(QV2)
        self.compositeview2.setMatrix(matrix)
        

        QV3 = QuadView(self, image_8bit3, zero_array, alpha_array,\
                            self.compositeview3, self.label21,\
                            self.SelectedTextBrowser_2, self.LivetextBrowser_2)
        self.compositescene3.clear()
        self.compositescene3.addItem(QV3)
        self.compositeview3.setMatrix(matrix)
        

        QV4 = QuadView(self, image_8bit4, zero_array, alpha_array,\
                            self.compositeview4, self.label22,\
                            self.SelectedTextBrowser_2, self.LivetextBrowser_2)
        self.compositescene4.clear()
        self.compositescene4.addItem(QV4)
        self.compositeview4.setMatrix(matrix)
Example #13
0
wb = Workbook()
ws = wb.active
ws.title = "Images"
dest_filename = 'name and images.xlsx'

for R in range(1, 1000):
    ws.row_dimensions[R].height = 200

wcolA = 25
#7
print("       Writing excel")
i = 0
for I in Search_images:
    i = i + 1
    img = Image(I)
    img.width = 200
    img.height = 200
    Cell1 = ("A" + str(i))
    Cell2 = ("B" + str(i))
    ws[Cell1] = I

    ws.add_image(img, Cell2)

ws.column_dimensions["A"].width = wcolA
ws.column_dimensions["B"].width = wcolA
ws.column_dimensions["C"].width = wcolA
ws.column_dimensions["D"].width = wcolA
wb.save(filename=dest_filename)
#8
print("        File ready")