ошибка: (-215: утверждение не удалось)! ssize.empty () в функции 'cv :: resize' OpenCV - PullRequest
0 голосов
/ 06 мая 2020

У меня есть этот старый код, который используется для нормальной работы в Python 2.7, а в go. Я только что обновил код для запуска в Python 3.8, но когда я пытаюсь выполнить его код в Python 3.8 и OpenCV 3.4, я получаю ошибку изменения размера и предупреждение (ниже)!

Вот ссылка на два изображения tif, которые требуются для запуска этого кода. Стоит отметить, что оба изображения tif находятся в той же папке, что и Python код

import cv2
import matplotlib.pyplot as plt
import numpy as np


## Code for C_preferred Mask and C_images##

## There are three outputs to this code:
#"Block_order_C.PNG"
#"Out_img.PNG" 
#"Output_C.txt"

## Change the image name here

filename_image = '2.tif'
filename_mask = '1.tif'

## OpenCV verison Checking
#print 'OpenCV version used', cv2.__version__
filename = open("Output_C.txt","w")
filename.write("Processing Image : " + str(filename_image) + '\n\n')

## Function to sort the contours : Parameters that you can tune : tolerance_factor and size 0f the image.Here, I have used a fix size of
## (800,800) 

def get_contour_precedence(contour, cols):
    tolerance_factor = 10
    origin = cv2.boundingRect(contour)
    return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]

## Loading the colored mask, resizing it to (800,800) and converting it from RGB to HSV space, so that the color values are emphasized
p_mask_c = cv2.cvtColor(cv2.resize(cv2.imread(filename_mask),(800,800)),cv2.COLOR_RGB2HSV);
# Loading the original Image
b_image_1 = cv2.resize(cv2.imread(filename_image),(800,800));

cv2.imshow("c_mask_preferred",p_mask_c)
cv2.waitKey();

# convert the target color to HSV, As our target mask portion to be considered is green. So I have chosen target color to be green
b = 0;
g = 255;
r = 0;

# Converting target color to HSV space

target_color = np.uint8([[[b, g, r]]])
target_color_hsv = cv2.cvtColor(target_color, cv2.COLOR_BGR2HSV)

# boundaries for Hue define the proper color boundaries, saturation and values can vary a lot
target_color_h = target_color_hsv[0,0,0]
tolerance = 20
lower_hsv = np.array([max(0, target_color_h - tolerance), 10, 10])
upper_hsv = np.array([min(179, target_color_h + tolerance), 250, 250])


# apply threshold on hsv image
mask = cv2.inRange(p_mask_c, lower_hsv, upper_hsv)
cv2.imshow("mask",mask)
cv2.waitKey()

# Eroding the binary mask, such that every white portion (grids) are seperated from each other, to avoid overlapping and mixing of
# adjacent grids
b_mask = mask;
kernel = np.ones((5,5))
#kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
sharp = cv2.erode(b_mask,kernel, iterations=2)

# Finding all the grids (from binary image)
contours, hierarchy = cv2.findContours(sharp,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print (' Number of contours', len(contours))

# Sorting contours
contours.sort(key=lambda x:get_contour_precedence(x, np.shape(b_mask)[0]))
#cv2.drawContours(b_image_1, contours, -1, (0,255,0), 1)

# Label variable for each grid/panel
label = 1;

b_image = b_image_1.copy();
temp =np.zeros(np.shape(b_image_1),np.uint8)
print (' size of temp',np.shape(temp), np.shape(b_image))
out_img = b_image_1.copy()
# Processing in each contour/label one by one
for cnt in contours:
    cv2.drawContours(b_image_1,[cnt],0,(255,255,0), 1)
    ## Just to draw labels in the center of each grid
    ((x, y), r) = cv2.minEnclosingCircle(cnt)
    x = int(x)
    y = int(y)
    r = int(r)    
    cv2.putText(b_image_1, "#{}".format(label), (int(x) - 10, int(y)),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
    ## 
    cv2.drawContours(temp,[cnt],0,(255,255,255), -1)
    #crop_img = np.bitwise_and(b_image,temp)
    r = cv2.boundingRect(cnt)
    crop_img = b_image[r[1]:r[1]+r[3], r[0]:r[0]+r[2]]
    mean = cv2.mean(crop_img);
    mean = np.array(mean).reshape(-1,1)
    print (' Mean color', mean, np.shape(mean))
    if mean[1] < 50:
        cv2.putText(out_img, "M", (int(x) - 10, int(y)),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 255), 1)
        filename.write("Block number #"+ str(label)+ ' is : ' + 'Magenta'+'\n'); 
    else:
        cv2.putText(out_img, "G", (int(x) - 10, int(y)),cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 255), 1)
        filename.write("Block number #"+ str(label)+  ' is : ' +'Gray'+'\n'); 
    label = label+1;    


cv2.imwrite("Block_order_C.PNG",b_image_1)
cv2.imwrite("Out_img.PNG",out_img)   
filename.close()   
cv2.imshow("preferred",b_image_1)
cv2.waitKey()

Ошибка

[WARN: 0] global C: \ projects \ opencv-python \ opencv \ modules \ imgcodecs \ src \ grfmt_tiff. cpp (449) cv :: TiffDecoder :: readData OpenCV TIFF: TIFFRGBAImageOK: К сожалению, не могу обрабатывать изображения с образцами с плавающей запятой IEEE Traceback (последний вызов последним): Файл «Processing_C_preferred.py», строка 32, в p_mask_ c = cv2.cvtColor (cv2.resize (cv2.imread (filename_mask), (800,800)), cv2.COLOR_RGB2HSV); cv2.error: OpenCV (4.2.0) C: \ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ resize. cpp: 4045: ошибка: (-215: утверждение не выполнено)! ssize.empty () в функции 'cv :: resize'

1 Ответ

1 голос
/ 06 мая 2020

Когда вы читаете изображение, передайте параметр cv::IMREAD_ANYDEPTH = 2 в качестве второго параметра в cv2.imread().

Измените ваши строки на

p_mask_c = cv2.cvtColor(cv2.resize(cv2.imread(filename_mask, 2),(800,800)),cv2.COLOR_RGB2HSV);

и

b_image_1 = cv2.resize(cv2.imread(filename_image, 2),(800,800));

удаляет ошибку изменения размера, которую вы видите.

Но вы получаете еще одну ошибку при изменении цвета, поскольку ваше изображение TIFF, по-видимому, имеет только один канал, поэтому cv2.COLOR_RGB2HSV не будет работать ..

Вы также можете использовать несколько флагов, например cv::IMREAD_COLOR = 1 ,

p_mask_c = cv2.cvtColor(cv2.resize(cv2.imread(filename_mask, 2 | 1),(800,800)),cv2.COLOR_BGR2HSV);

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

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