Imwrite saves images as black .
I am trying to write a program that finds center of black objects and cuts around that area. I applied it in 2 different data sets, in first it worked as expected but in second when I tried to save images it only saved full black images. here is my code:
img = '/Users/khand/OneDrive/Desktop/Thesis/case_db_10/' + el
print(type(img))
print(img)
im = cv2.imread(img).convert('RGBA')
print(type(im))
#plt.imshow(im)
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY_INV)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
na = 0
for c in range(0,len(cnts)):
cnt = cnts[c]
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
imag_jpg = '/Users/khand/OneDrive/Desktop/Thesis/case_db_10/' + nam +'.jpg'
imag_png = '/Users/khand/OneDrive/Desktop/Thesis/case_db_10/' + im_nam2[0] + '.png'
image_jpg = cv2.imread(imag_jpg)
image_png = cv2.imread(imag_png)
y1 = cx-100
y2 = cx+100
x1 = cy-100
x2 = cy+100
if x2 > 2000:
x2 = 2000
x1 = 1800
if y2 > 2000:
y2 = 2000
y1 = 1800
if x1 < 0:
x1 = 0
x2 = 200
if y1 <0:
y1 = 0
y2 = 200
crop_imag_jpg = image_jpg[x1:x2, y1:y2].copy()
crop_imag_png = image_png[x1:x2, y1:y2].copy()
#ima_name_jpg = '/Users/khand/OneDrive/Desktop/Thesis/Case_db/org/cropped_jpg_' +str(nam_num)+'_'+str(im_nam2_num)+'_'+str(na)+'.jpg'
#ima_name_png = '/Users/khand/OneDrive/Desktop/Thesis/Case_db/png/cropped_png_' +str(nam_num)+'_'+str(im_nam2_num)+'_'+str(na)+'.png'
ima_name_jpg = '/Users/khand/OneDrive/Desktop/Thesis/Case_db/org10/'+ nam +str(nam_num)+'_'+str(im_nam2_num)+'_'+str(na)+'.jpg'
ima_name_png = '/Users/khand/OneDrive/Desktop/Thesis/Case_db/png10/'+ nam +str(nam_num)+'_'+str(im_nam2_num)+'_'+str(na)+'.png'
cv2.imwrite(ima_name_jpg,crop_imag_jpg)
cv2.imwrite(ima_name_png,crop_imag_png)
The difference in images are in their bit depth, in the working one it is 32 the one which is not working is 8. I am not sure if it is related to this or not. If you have any idea please feel free to help :) Thanks.! This one is working and 32 bit depth:
This one is not working and 8 bit depth:
post original images(jpg, png)
I edited original post and added images.
Can you rename extension png to jpg to see if you get 32 bit?
Btw. Use variable name such as
crop_imag_jpg1
andcrop_imag_jpg2
andima_name_jpg1
andima_name_jpg2
thanks I solved it simple adding 2 lines:
like this, but now I have a different problem. When I read using cv2.imread it gives noneType, Could you please help in this case ?
I solved it as well but still it gives full black images
Did you change extension both jpg when using
imwrite
?Yeah I did but it didn't change the result.
It my lunch time.