OpenCV не может прочитать файл в приложении фляги - PullRequest
0 голосов
/ 27 апреля 2019

У меня есть приложение-колба, которое позволяет пользователю загрузить изображение, а затем выполнить многоэтапную обработку.

Я пытаюсь прочитать загруженное изображение в cv2, используя cv2.imread, но функция никогда не возвращает, просто зависает в cv2.imread

метод вызова

def remove_skin_color(filename):
    print('removing skin color for {}'.format(filename))
    colorDetection = ColorDetector()
    img_loc = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)
    print('processing image {}'.format(img_loc))
    no_skin_img = colorDetection.get_removed_skin(img_loc=img_loc)
    cv2.imwrite(os.path.join(app.root_path, IMG_FOLDER, filename), no_skin_img)
    print('writing image done')
    return filename

Журналы

[Sat Apr 27 14:05:53.119646 2019] [wsgi:error] [pid 12364:tid 1328] [client 197.125.110.218:39284] request method is POST\r
[Sat Apr 27 14:05:53.122573 2019] [wsgi:error] [pid 12364:tid 1328] [client 197.125.110.218:39284] True\r
[Sat Apr 27 14:05:53.122573 2019] [wsgi:error] [pid 12364:tid 1328] [client 197.125.110.218:39284] receiving ...  file.JPEG\r
[Sat Apr 27 14:05:53.122573 2019] [wsgi:error] [pid 12364:tid 1328] [client 197.125.110.218:39284] 1556366753_file.JPEG\r
[Sat Apr 27 14:05:53.126479 2019] [wsgi:error] [pid 12364:tid 1328] [client 197.125.110.218:39284] removing skin color for 1556366753_file.JPEG\r
[Sat Apr 27 14:05:53.126479 2019] [wsgi:error] [pid 12364:tid 1328] [client 197.125.110.218:39284] processing image C:\\wamp64\\www\\app\\uploads\\1556366753_file.JPEG\r

вызываемый метод

 def get_removed_skin(self, bn_img=None, img_loc=None):
        try:
            if img_loc:
                sourceImage = cv2.imread(img_loc) #code hangs here
            else:
                sourceImage = bn_img

        except Exception as e:

            print(e)

        # Constants for finding range of skin color in YCrCb
        min_YCrCb = np.array([0, 133, 77], np.uint8)
        max_YCrCb = np.array([255, 173, 127], np.uint8)

        # Convert image to YCrCb
        imageYCrCb = cv2.cvtColor(sourceImage, cv2.COLOR_BGR2YCR_CB)

        # Find region with skin tone in YCrCb image
        skinRegion = cv2.inRange(imageYCrCb, min_YCrCb, max_YCrCb)

        # Do contour detection on skin region
        _, contours, hierarchy = cv2.findContours(skinRegion, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        cv2.fillPoly(sourceImage, pts=contours, color=(255, 255, 255))

        return sourceImage

note : я запускаю это приложение на сервере Wamp (Apache) + WSGI на моем ноутбуке

виртуальный хост conf

# Virtual Hosts
#
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  ErrorLog ${INSTALL_DIR}/www/app/app.log
   WSGIScriptAlias / "${INSTALL_DIR}/www/app/web.wsgi"
  DocumentRoot "${INSTALL_DIR}/www/app"
  <Directory "${INSTALL_DIR}/www/app/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews +ExecCGI
    AllowOverride All
    #Require local
    Require all granted
  </Directory>
</VirtualHost>

когда я запускаю приложение локально, оно работает как положено, без проблем

Я упростил процесс, как показано ниже, и все еще та же проблема

def upload_file():
    print('request method is {}'.format(request.method))
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            print('file not in request.files')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            print('filename is {}'.format(file.filename))
            return redirect(request.url)
        print(file and allowed_file(file.filename))
        if file and allowed_file(file.filename):
            print('receiving ... ', file.filename)
            filename = secure_filename(file.filename)
            ts = int(time.time())
            file_name = file_name_template.format(ts, filename)
            print(file_name)
            filePath = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], file_name)

            file.save(filePath)
            # file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))

            img = cv2.imread(filePath) 
            print(' file has been read') #this line never gets printed
             out_image_name = remove_skin_color(file_name)

            json_data = color_palette(out_image_name)

            return json_data

1 Ответ

0 голосов
/ 29 апреля 2019

решение было добавить WSGIScriptAlias application-group=%{GLOBAL} в файл виртуальных хостов, проблема заключается в

с модулем расширения, не предназначенным для работы в суб-интерпретаторе.Вышеуказанное заставляет его работать в главном интерпретаторе.

пожалуйста, обратитесь к this и this

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...