0

I'm trying to make a gui that helps me cropping faces and foldering them according to their moods such as angry, sad, happy, etc. My code looks like working fine but when I crop an image it saves the rest of image. I really don't know how can I accomplish that!! My cropping fuctions:

    def on_mouse(self, event, x, y, buttons, user_param):
    # Mouse callback that gets called for every mouse event (i.e. moving, clicking, etc.)

    if self.done: # Nothing more to do
        return

    if event == cv2.EVENT_MOUSEMOVE:
        # We want to be able to draw the line-in-progress, so update current mouse position
        self.current = (x, y)
    elif event == cv2.EVENT_LBUTTONDOWN:
        # Left click means adding a point at current position to the list of points
        print("Adding point #%d with position(%d,%d)" % (len(self.points), x, y))
        self.points.append((x, y))
    elif event == cv2.EVENT_RBUTTONDOWN:
        # Right click means we're done
        print("Completing polygon with %d points." % len(self.points))
        self.done = True


def run(self, image):
    # Let's create our working window and set a mouse callback to handle events
    cv2.namedWindow(self.window_name, flags=cv2.WINDOW_AUTOSIZE)
    cv2.imshow(self.window_name, image)
    cv2.waitKey(1)
    cv2.setMouseCallback(self.window_name, self.on_mouse)

    while(not self.done):
        # This is our drawing loop, we just continuously draw new images
        # and show them in the named window
        if (len(self.points) > 0):
            # Draw all the current polygon segments
            cv2.polylines(image, np.array([self.points]), False, FINAL_LINE_COLOR, 1)
            # And  also show what the current segment would look like
            cv2.line(image, self.points[-1], self.current, WORKING_LINE_COLOR)
        # Update the window
        cv2.imshow(self.window_name, image)
        # And wait 50ms before next iteration (this will pump window messages meanwhile)
        if cv2.waitKey(50) == 27: # ESC hit
            self.done = True

    # User finised entering the polygon points, so let's make the final drawing
    # of a filled polygon
    if (len(self.points) > 0):
        cv2.fillPoly(image, np.array([self.points]), FINAL_LINE_COLOR)
    # And show it
    cv2.imshow(self.window_name, image)
    # Waiting for the user to press any key
    cv2.waitKey()

    cv2.destroyWindow(self.window_name)
    return image

I added the whole code here if you need

Edit : When I changed this lines in open function:

fileName = unicode(fileName.toUtf8(), encoding="UTF-8")
img = cv2.imread(fileName)

To this:

im = Image.open(fileName).convert("RGBA")
imArray = numpy.asarray(im)
real_image = imageViewer.run(imArray)

It gaves me this errors: Connected to pydev debugger (build 162.1967.10) Corrupt JPEG data: premature end of data segment Traceback (most recent call last): File "C:/Users/ASUS/Desktop/cgg/gui/template2.py", line 156, in open im = Image.open(fileName).convert("RGBA") File "C:\Python27\lib\site-packages\PIL\Image.py", line 1956, in open prefix = fp.read(16) AttributeError: 'QString' object has no attribute 'read'

I get the file name with this code lines by the way

fileName = QtGui.QFileDialog.getOpenFileName(self, "Open File",
            QtCore.QDir.currentPath())
if fileName:
   image = QtGui.QImage(fileName)
   if image.isNull():
      QtGui.QMessageBox.information(self, "Image Viewer",
                    "Cannot load %s." % fileName)
            return
user1234
  • 145
  • 5
  • 20
  • 3
    You can create a polygon mask and apply it to the image, like this answer explains: http://stackoverflow.com/questions/22588074/polygon-crop-clip-using-python-pil – Christopher Shroba Nov 17 '16 at 13:51
  • @ChristopherShroba thank you but I'm getting the picture's file name from a QtGui FileDialog object thats way i cannot use it like : im = Image.open(fileName).convert("RGBA") It gives me an error message: Traceback (most recent call last): File "C:/Users/ASUS/Desktop/cgg/gui/template2.py", line 156, in open im = Image.open(fileName).convert("RGBA") File "C:\Python27\lib\site-packages\PIL\Image.py", line 1956, in open prefix = fp.read(16) AttributeError: 'QString' object has no attribute 'read' Do you have any advice to fix that? – user1234 Nov 17 '16 at 14:06
  • It seems like maybe your FileDialog is returning a QString object instead of just a normal string, and the image library is expecting a normal string, so I would guess that there's some way of converting it to a normal string. If you're still having trouble, could you add the error to your question so it's more nicely formatted? And could you include the code that's generating the error? – Christopher Shroba Nov 17 '16 at 14:18
  • In order to read in a QString object as python string, you can just use pythons `str()` method. In order to prevent something like this in general, you could try to use `import sip ` [`sip.setapi('QString', 2)`](http://stackoverflow.com/questions/6238193/pyqt-new-api-with-python-2) at the start of your script (before loading QT). – ImportanceOfBeingErnest Nov 20 '16 at 23:19

0 Answers0